💡Python's Built-in Constants: True, False, None, and More
Why Python's built-in constants are more than just keywords
TL;DR
Python has six pre-declared 'constants', including True, False, and None. These aren't just keywords but have unique behaviors, like __debug__ flipping to False with -O.
Python includes six pre-declared constants: True, False, None, __debug__, Ellipsis (or ...), and NotImplemented. Unlike typical identifiers, these are their own lexical tokens. For instance, attempting to use x.True raises a SyntaxError. The catch? While True, False, and None can be manipulated using getattr and setattr, the value of __debug__ remains unaffected by changes in builtins. Ellipsis and NotImplemented have peculiar behaviors too: they're not real constants but can still be shadowed globally. This matters for developers working with Python's internals or building tools that rely on these constants.
Key Points
True, False, and None are keywords in Python, used for boolean logic and null values.
__debug__ is a boolean constant that flips to False when running with -O optimization flag.
Ellipsis (or ...) can be shadowed globally but its value remains unchanged despite attempts to modify it.
NotImplemented is documented as part of the 'constants' section in Python's reference, not truly immutable.
Using getattr and setattr on True, False, and None allows their values to be changed, unlike __debug__.
Why It Matters
If you're working with Python's built-in features or building tools that rely on these constants, understanding the nuances of True, False, None, __debug__, Ellipsis, and NotImplemented is crucial. For instance, attempting to use x.True will raise a SyntaxError due to their unique lexical token status.
Frequently Asked Questions
Why does this matter?
If you're working with Python's built-in features or building tools that rely on these constants, understanding the nuances of True, False, None, __debug__, Ellipsis, and NotImplemented is crucial. For instance, attempting to use x.True will raise a SyntaxError due to their unique lexical token status.
What happened?
Python has six pre-declared 'constants', including True, False, and None. These aren't just keywords but have unique behaviors, like __debug__ flipping to False with -O.
Comments
Be the first to comment
Enjoyed this article?
Get it daily. 7am. Free. Reads in 5 minutes.
Join 3,315 builders reading daily.