Short answer
Yes … but not in the “C-style, the interpreter will raise if you reassign it” sense.
Python doesn’t have a real const keyword, so anything you put inside a function is, technically, an ordinary local variable that you could rebind later.
What you can do is adopt one of the conventions/mechanisms below so that humans (and lint/type-checking tools) treat the value as a constant.
Plain old naming convention (most common)
python
def area_of_circle(r):
PI = 3.141592653589793 # ALL_CAPS announces “don’t touch me”
return PI * r * r
Nothing stops someone from doing PI = 10 two lines later; you’re relying on discipline.
typing.Final (Python 3.8+; enforced by type-checkers like mypy, pyright)
python
from typing import Final
def rocket_launch_time():
SPEED_OF_LIGHT: Final = 299_792_458 # m/s
# mypy will complain if we try to reassign
At runtime this is still just a variable, but static analysis will flag re-assignment.
Default-argument “constants”
Default parameter values are evaluated once—when the function is defined, not each time it’s called.
python
def fibonacci(n, _phi=(1 + 5 ** 0.5) / 2): # _phi acts like a constant
return int(_phi ** n / 5 ** 0.5 + 0.5)
You still could mutate the object if it’s mutable, but you can’t rebind _phi without shadowing.
Enums for a fixed set of named values
python
from enum import Enum, auto
class Color(Enum):
RED = auto()
GREEN = auto()
BLUE = auto()
def paint(color: Color):
...
Inside the function you refer to Color.RED, Color.GREEN, etc. You can’t create new members at runtime.
“Frozen” objects
If your “constant” is a mapping or record, make it immutable:
Module-level constants (idiomatic)
Unless the value must be computed during every call, the Pythonic place for constants is the module level:
python
PI = 3.14159 # module constant
def circumference(r):
return 2 * PI * r
This avoids recomputing the literal each call and makes the intent unambiguous.
Take-away
• You can absolutely “declare” a constant inside a function, but Python won’t enforce immutability for you.
• Use ALL_CAPS or Final if you just need a reminder / static-analysis help.
• For truly immutable data, pick an immutable type (tuple, frozenset, MappingProxyType, Enum, frozen dataclass, …).
• When in doubt, put the constant at module scope—most readers will expect to find it there.