Constants are like variables except that once they are defined they cannot be changed or undefined. Show
PHP ConstantsA constant is an identifier (name) for a simple value. The value cannot be changed during the script. A valid constant name starts with a letter or underscore (no $ sign before the constant name). Note: Unlike variables, constants are automatically global across the entire script. Create a PHP ConstantTo create a constant, use the Syntaxdefine(name, value, case-insensitive) Parameters:
ExampleCreate a constant with a case-sensitive name: <?php Try it Yourself » ExampleCreate a constant with a case-insensitive name: <?php Try it Yourself » PHP Constant ArraysIn PHP7, you can create an Array constant using the ExampleCreate an Array constant: <?php Try it Yourself » Constants are GlobalConstants are automatically global and can be used across the entire script. ExampleThis example uses a constant inside a function, even if it is defined outside the function: <?php function myTest() { myTest(); Try it Yourself » In programming, the term constant refers to names representing values that don’t change during a program’s execution. Constants are a fundamental concept in programming, and Python developers use them in many cases. However, Python doesn’t have a dedicated syntax for defining constants. In practice, Python constants are just variables that never change. To prevent programmers from reassigning a name that’s supposed to hold a constant, the Python community has adopted a naming convention: use uppercase letters. For every Pythonista, it’s essential to know what constants are, as well as why and when to use them. In this tutorial, you’ll learn how to:
By learning to define and use constants, you’ll dramatically improve your code’s readability, maintainability, and reusability. To learn the most from this tutorial, you’ll need basic knowledge of Python variables, functions, modules, packages, and namespaces. You’ll also need to know the basics of object-oriented programming in Python. Understanding Constants and VariablesVariables and constants are two historical and fundamental concepts in computer programming. Most programming languages use these concepts to manipulate data and work in an effective and logical fashion. Variables and constants will probably be present in each project, app, library, or other piece of code that you’ll ever write. The question is: what are variables and constants in practice? What Variables AreIn math, a variable is defined as a symbol that refers to a value or quantity that can change over time. In programming, a variable is also a symbol or name typically associated with a memory address containing a value, object, or piece of data. Like in math, the content of a programming variable can change during the execution of the code that defines it. Variables typically have a descriptive name that’s somehow associated with a target value or object. This target value can be of any data type. So, you can use variables to represent numbers, strings, sequences, custom objects, and more. You can perform two main operations on a variable:
In most programming languages, you can access the value associated with a variable by citing the variable’s name in your code. To assign a new value to a given variable, you’ll use an assignment statement, which often consists of the variable’s name, an assignment operator, and the desired value. In practice, you’ll find many examples of magnitudes, data, and objects that you can represent as variables. A few examples include temperature, speed, time, and length. Other examples of data that you can treat as variables include the number of registered users in a web app, the number of active characters in a video game, and the number of miles covered by a runner. What Constants AreMath also has the concept of constants. The term refers to a value or quantity that never changes. In programming, constants refer to names associated with values that never change during a program’s execution. Just like variables, programming constants consist of two things: a name and an associated value. The name will clearly describe what the constant is all about. The value is the concrete expression of the constant itself. Like with variables, the value associated with a given constant can be of any of data type. So, you can define integer constants, floating-point constants, character constants, string constants, and more. After you’ve defined a constant, it’ll only allow you to perform a single operation on it. You can only access the constant’s value but not change it over time. This is different from a variable, which allows you to access its value, but also reassign it. You’ll use constants to represent values that won’t change. You’ll find lots of these values in your day-to-day programming. A few examples include the speed of light, the number of minutes in an hour, and the name of a project’s root folder. Why Use ConstantsIn most programming languages, constants protect you from accidentally changing their values somewhere in the code when you’re coding at two in the morning, causing unexpected and hard-to-debug errors. Constants also help you make your code more readable and maintainable. Some advantages of using constants instead of using their values directly in your code include:
As you’ve learned in this table, constants are an important concept in programming for good reason. They can make your life more pleasant and your code more reliable, maintainable, and readable. Now, when should you use constants? When Use ConstantsLife, and particularly science, is full of examples of constant values, or values that never change. A few examples include:
All the above examples are constant values that people commonly use in life and science. In programming, you’ll often find yourself dealing with these and many other similar values that you can consider and treat as constants. In summary, use a constant to represent a quantity, magnitude, object, parameter, or any other piece of data that’s supposed to remain unchanged during its lifetime. Defining Your Own Constants in PythonUp to this point, you’ve learned about constants as a general concept in life, science, and programming. Now it’s time to learn how Python deals with constants. First, you should know that Python doesn’t have a dedicated syntax for defining constants. In other words, Python doesn’t have constants in the strict sense of the word. It only has variables, primarily because of its dynamic nature. Therefore, to have a constant in Python, you need to define a variable that never changes and stick to that behavior by avoiding assignment operations on the variable itself. Then, how would Python developers know that a given variable represents a constant? The Python community has decided to use a strong naming convention to distinguish between variables and constants. Keep reading to learn more! User-Defined ConstantsTo tell other programmers that a given value should be treated as a constant, you must use a widely accepted naming convention for the constant’s identifier or name. You should write the name in capital letters with underscores separating words, as stated in the Constants section of PEP 8. Here are a few example of user-defined Python constants:
Note that you’ve created these constants exactly as you’d create variables. You’ve used a descriptive name, the assignment operator ( By using capital letters only, you’re communicating that the current name is intended to be treated as a constant—or more precisely, as a variable that never changes. So, other Python developers will know that and hopefully won’t perform any assignment operation on the variable at hand. Because Python constants are just variables, both follow similar naming rules, with the only distinction being that constants use uppercase letters only. Following this idea, constants’ names can:
Using uppercase letters makes your constants stand out from your variables. This way, other developers will unambiguously recognize their purpose. As a general naming recommendation, avoid abbreviated names
when defining constants. The purpose of a constant’s name is to clarify the meaning of the constant’s value so that you can reuse it later. This goal demands descriptive names. Avoid using single-letter names, uncommon abbreviations, and generic names like The recommended practice is to define constants at the top of any Module-Level Dunder ConstantsModule-level dunder names are special names that start and end with a double underscore. Some
examples include names such as According to Python’s coding style guide, PEP 8, module-level dunder names should appear after the module’s docstring and before any Here’s a sample module that includes a bunch of dunder names:
In this example, In contrast, Note that the >>>
In general, there are no hard rules that prevent you from defining your own module-level dunder names. However, the Python documentation strongly warns against using dunder names other than those generally accepted and used by the community. The core developers may introduce new dunder names to the language in the future without any warning. Putting Constants Into ActionSo far, you’ve learned about constants and their role and importance in programming. You’ve also learned that Python doesn’t support strict constants. That’s why you can think of constants as variables that never change. In the following sections, you’ll code examples of how valuable constants can be in your day-to-day coding adventure. Replacing Magic Numbers for ReadabilityIn programming, the term magic number refers to any number that appears directly in your code without any explanation. It’s a value that comes out of the blue, making your code enigmatic and difficult to understand. Magic numbers also makes programs less readable and more difficult to maintain and update. For example, say you have the following function:
Can you tell up front what the meaning of each number in this computation is? Probably not. The different numbers in this function are magic numbers because you can’t reliably infer their meanings from the numbers themselves. Check out the following refactored version of this function:
With these minor updates, your function now reads like a charm. You and any other developers reading your code can surely tell what this function does because you’ve replaced the original magic numbers with appropriately named constants. The name of each constant clearly explains its corresponding meaning. Every time you find yourself using a magic number, take the time to replace it with a constant. This constant’s name must be descriptive and unambiguously explain the meaning of the target magic number. This practice will automatically improve the readability of your code. Reusing Objects for MaintainabilityAnother everyday use case of constants is when you have a given value repeatedly appearing in different parts of your code. If you insert the concrete value into the code at every required place, then you’ll be in trouble if you ever need to change the value for any reason. In this situation, you’ll need to change the value in every place. Changing the target value in multiple places at a time is error-prone. Even if you rely on your editor’s Find and Replace feature, you can leave some unchanged instances of the value, which can lead to unexpected bugs and weird behaviors later. To prevent these annoying issues, you can replace the value with a properly named constant. This will allow you to set the value once and repeat it in as many locations as needed. If you ever need to change the constant’s value, then you just have to change it in a single place: the constant definition. For example, say you’re writing a
This example uncovers how the approximate value of Pi ( Using a named constant to store the value of Pi is an excellent approach to solving these issues. Here’s an enhanced version of the above code:
This version of Another advantage is that now your code is more readable and easier to understand. The constant’s name is self-explanatory and reflects the accepted math terminology. Declaring a constant once and then reusing it several times, as you did in the above example, represents a significant maintainability improvement. If you ever have to update the constant’s value, then you’ll update it a single place rather than in multiple places, which implies way less effort and error risk. Providing Default Argument ValuesUsing named constants to provide default argument values to functions, methods, and classes is another common practice in Python. There are lots of examples of this practice in the Python standard library. For example, the The class constructor of In this example, The Another example of when constants come in handy as default argument values is when you have several functions with a recurrent argument. Say that you’re developing an application that connects to a local SQLite database. Your app uses the following set of functions to manage the database:
These functions perform different actions on your SQLite database. Note that all your functions share the While you’re developing the application, you decide to provide a default database path to your functions so that you can quickly test them. In this case, you can directly use the path as a default value to the However, it’s better to use a named constant to provide the default database path:
This small update enables you to quickly test your app by targeting a sample database during development. It also improves the maintainability of your code because you can reuse this constant in other database-related functions that appear in future versions of your app. Finally, you’ll find situations in which you want to pass an object with certain behavior to a class, method, or function. This practice is typically known as duck typing and is a fundamental principle in Python. Now say that your code will take care of providing a standard implementation of the required object. If your users want a custom object, then they should provide it themselves. In this situation, you can use a constant to define the default object and then pass this constant as a default argument value to the target class, method, or function. Check
out the following example of a hypothetical
This class provides a way to manipulate different types of files. The Here’s a toy implementation of a reader class:
The Your users can also code custom readers. For example, they can code readers for CSV and JSON files. Once they’ve written a given
reader, they can pass it into the Handling Your Constants in a Real-World ProjectNow that you know how to create constants in Python, it’s time to learn how to handle and organize them in a real-world project. You can use several approaches or strategies to this end. For example, you can put your constants in:
In the following sections, you’ll write some practical examples that demonstrate the above strategies for managing constants appropriately. Creating a Dedicated Module for ConstantsAnother common strategy for organizing and managing your constants is creating a dedicated module in which to put them all. This strategy is appropriate for constants that are used in many modules and even packages across a given project. The central idea of this strategy is to create an intuitive and unique namespace for constants. To apply this strategy to your calculations example, you can create a Python package containing the following files:
The
Once you’ve added this code to
Note that you import the To use your >>>
Now your Storing Constants in Configuration FilesNow say that you want to go further when it comes to externalizing the constants of a given project. You may need to keep all your constants out of your project’s source code. To do this, you can use an external configuration file. Here’s an example of how to move your constants to a configuration file:
This file uses the INI file format. You can read this type of file using the Now get back to
In this example, your code first reads the
configuration file and stores the resulting Note that This strategy may be beneficial when you’re creating a graphical user interface (GUI) app and need to set some parameters to define the shape and size of the app’s windows when loading and showing the GUI, for example. Handling Constants as Environment VariablesAnother helpful strategy to handle your constants is to define them as system variables if you’re on Windows or environment variables if you’re on macOS or Linux. This approach is commonly used to configure deployment in different environments. You can also use environment variables for constants that imply security risks and shouldn’t be directly committed to the source code. Examples of these types of constants include authentication credentials, API access tokens, and so on. To use this strategy, you first must export your constants as environment or system variables in your operating system. There are at least two ways to do this:
The first technique is pretty quick and practical. You can use it to run some fast tests on your code. For example, say that you need to export an API token as a system or environment variable. In that case, you just need to run the following command:
The main drawback of this technique is that your constants will be accessible only from the command-line session in which you defined them. A much better approach is to make your operating system load the constants whenever you fire up a command-line window. If you’re on Windows, then check out the
Configuring Environment Variables section in Your Python Coding Environment on Windows: Setup Guide to learn how to create system variables. Follow the instructions in this guide and add an If you’re on Linux or macOS, then you can go to your home folder and open your shell’s configuration file. Once you’ve opened that file, add the following line at the end of it:
Linux and macOS automatically load the corresponding shell configuration file whenever you start a terminal or command-line window. This way, you
ensure that the Once you’ve defined the required environment variables for your Python constant, then you need to load them into your code. To do this, you can use the Your >>>
Using environment variables to store constants, and the Exploring Other Constants in PythonApart from user-defined constants, Python also defines several internal names that can be considered as constants. Some of these names
are strict constants, meaning that you can’t change them once the interpreter is running. This the case for the In the following sections, you’ll learn about some internal Python names that you can consider and should treat as constants in your code. To kick things off, you’ll review some built-in constants and constant values. Built-in ConstantsAccording to the Python documentation, “A small number of constants live in the built-in namespace” (Source). The first two constants listed in the docs are >>>
Note that the Another important and commonplace constant value is >>>
The ellipsis literal ( >>>
You can use >>>
The Another interesting and potentially useful built-in
constant is >>>
The To change the value of Internal Dunder NamesPython also has a broad set of internal dunder names that you can consider as constants. Because there are several of these special names, you’ll just learn about The Fire up your code editor and create the following sample module:
Once you have this file in place, get back to your command-line window and run the following command:
With the Alternatively, if you take
Note that now The As an example of how
If you import the
Likewise, if you run
In short, Python sets Useful String and Math ConstantsYou’ll find many useful constants in the
standard library. Some of them are tightly connected to some specific modules, functions, and classes. Others are more generic, and you can use them in various scenarios. That’s the case with some math and string-related constants that you can find in the The >>>
These constants will come in handy whenever you’re writing math-related code or even code that just uses them to perform specific computations, like your Here’s an updated implementation of
This updated version of The The
These string-related constants come in handy in many situations. You can use them when you’re doing a lot of string processing, working with regular expressions, processing natural language, and more. Type-Annotating ConstantsSince Python 3.8, the Here are some examples of using
The Defining Strict Constants in PythonUp to this point, you’ve learned a lot about programming and Python constants. You now know that Python doesn’t support strict constants. It just has variables. Therefore, the Python community has adopted the naming convention of using uppercase letters to communicate that a given variable is really a constant. So, in Python, you don’t have constants. Rather, you have variables that never change. This can be an issue if you’re working on a large Python project with many programmers at different levels. In this situation, it’d be nice to have a mechanism that guarantees strict constants— constants that no one can change after the program has started. Because Python is a pretty flexible programming language, you’ll find several ways to achieve the goal of making your constant unchangeable. In the following few sections, you’ll learn about some of these ways. They all imply creating a custom class and using it as a namespace for constants. Why should you use a class as the namespace for your constants? In Python, any name can be rebound at will. At the module level, you don’t have the appropriate tools to prevent this from happening. So, you need to use a class because classes provide way more customization tools than modules. In the following sections, you’ll learn about several different ways to use a class as your namespace for strict constants. The .__slots__ AttributePython classes allow you to define a special class attribute called You won’t be able to add new instance attribute to a class with a Using >>>
In this example, you define
The next step is to instantiate the class to create a variable holding the namespace with all your constants. Note that you can quickly access any constant in your special namespace, but you can’t assign it a new value.
If you try to do it, then you get an With this technique, you’re guaranteeing that no one else on your team can change the value of your constants. You’ve achieved the expected behavior of a strict constant. The @property DecoratorYou can also take advantage of the
>>>
Because you don’t provide setter methods for the The namedtuple() Factory FunctionPython’s Like regular tuples, named tuple instances are immutable, which implies that you can’t modify an existing named tuple object in place. Being immutable sounds appropriate for creating a class that works as a namespace of strict constants. Here’s how to do it: >>>
In this example, your constants play the role of fields in the underlying named tuple, Because tuples are immutable, there’s no way for you to modify the value of any field. So, your The @dataclass DecoratorData classes are classes that contain mainly data, as their name indicates. They can also have methods, but that’s not their primary goal. To create a data class, you need to use the How can you use this type of class to create a namespace of strict constants? The Here’s how you can use a data class to create a namespace containing your constants: >>>
In this example, you first import the You can create an instance of this class and use it as your constants namespace. Again, you can access all the constants, but you can’t modify their values, because the data class is frozen. The .__setattr__() Special MethodPython classes let you define a special method called In practice, you can override >>>
Your custom implementation of ConclusionNow you know what constants are, as well as why and when to use them in your code. You also know that Python doesn’t have strict constants. The Python community uses uppercase letters as a naming convention to communicate that a variable should be used as a constant. This naming convention helps to prevent other developers from changing variables that are meant to be constant. Constants are everywhere in programming, and Python developers also use them. So, learning to define and use constants in Python is an important skill for you to master. In this tutorial, you learned how to:
With this knowledge about what constants are, why they’re important, and when to use them, you’re ready to start improving your code’s readability, maintainability, and reusability immediately. Go ahead and give it a try! What is an a value that does not change?A constant is something whose value does not change.
What is a variable called that should remain unchanged throughout your program?A constant variable, or simply a constant, is a variable whose value should not be changed after it has been assigned an initial value.
Can a named constant change?Since a named constant is just a variable, it can change any time during a program's execution.
What type of function can be used to determine whether number is even or odd?If a number is evenly divisible by 2 with no remainder, then it is even. You can calculate the remainder with the modulo operator % like this num % 2 == 0 . If a number divided by 2 leaves a remainder of 1, then the number is odd. You can check for this using num % 2 == 1 .
|