Yes, you can define a variable inside a function using the ALL_CAPS_SNAKE_CASE naming convention that Python uses for constants. However, it's generally not recommended for true "constants" in the typical sense, because of scope and the nature of constants.
Let's break it down:
What You Can Do (Technically)
You can write code like this:
def my_function():
# This is a local variable, named like a constant
LOCAL_VALUE = 10
OTHER_SETTING = "some string"
result = LOCAL_VALUE * 2
print(f"Inside function: {result}, {OTHER_SETTING}")
# You *could* even reassign it within the function,
# though that would defeat the "constant" convention
# LOCAL_VALUE = 20
When my_function() is called, LOCAL_VALUE and OTHER_SETTING are created and assigned. They behave like any other local variable.
Why It's Generally Not Recommended for True Constants
-
Scope: Variables defined inside a function are local to that function. They cannot be accessed from outside the function. If a value is truly a constant, it often means it's a fixed value that might be needed in multiple places across your module or application.
def my_function():
LOCAL_CONST = 10
print(LOCAL_CONST)
my_function() # Output: 10
# print(LOCAL_CONST) # This would raise a NameError, as LOCAL_CONST is not defined here
-
Re-creation: Every time the function is called, these "constants" are re-created and assigned. While for simple types (numbers, strings) this has negligible performance impact, it conceptually doesn't fit the idea of a fixed, universally available constant.
-
No Enforcement: Python doesn't have true const or final keywords. The ALL_CAPS naming convention is purely a convention. You can reassign LOCAL_VALUE within the function if you wanted to, though doing so would be terrible practice.
Where Constants Should Usually Be Defined
For values that are truly constant (i.e., they don't change during the program's execution and are meant to be widely available), they are typically defined at the module level (i.e., at the top of a .py file).
1. Module-Level Constants (Most Common)
# my_module.py
# These are true constants, accessible throughout this module
MAX_RETRIES = 3
DEFAULT_TIMEOUT_SECONDS = 60
API_KEY_LENGTH = 32
def make_api_call():
print(f"Making API call with timeout: {DEFAULT_TIMEOUT_SECONDS}s")
# ... use MAX_RETRIES if needed ...
def process_data():
print(f"Max retries allowed: {MAX_RETRIES}")
# ...
You can then import these constants into other modules:
# another_script.py
from my_module import MAX_RETRIES, make_api_call
print(f"Global max retries: {MAX_RETRIES}")
make_api_call()
2. Class-Level Constants
If a constant is inherently tied to a specific class, you can define it as a class attribute.
class Circle:
PI = 3.14159 # A constant related to Circle objects
DEFAULT_RADIUS = 1.0
def __init__(self, radius=None):
self.radius = radius if radius is not None else Circle.DEFAULT_RADIUS
def get_circumference(self):
return 2 * Circle.PI * self.radius
c = Circle()
print(f"Default radius: {c.DEFAULT_RADIUS}") # Access via instance
print(f"Pi value: {Circle.PI}") # Access via class
3. Using enum.Enum (For sets of related constants)
For a collection of distinct, related constants, enum.Enum is the most Pythonic and robust way.
from enum import Enum
class Status(Enum):
PENDING = 1
RUNNING = 2
COMPLETED = 3
FAILED = 4
def get_task_status(task_id):
# Simulate fetching status
if task_id == 1:
return Status.RUNNING
elif task_id == 2:
return Status.COMPLETED
else:
return Status.PENDING
current_status = get_task_status(1)
if current_status == Status.RUNNING:
print("Task is currently running.")
print(f"Status value for PENDING: {Status.PENDING.value}")
Conclusion
While you can technically create a local variable inside a function and name it using the constant convention, it doesn't serve the typical purpose of a "constant" in Python. Constants are usually defined at the module level, as class attributes, or using enum.Enum to ensure they have the appropriate scope and convey their unchanging nature effectively.