Proposal: Strict Mode for Protecting Built-in Functions
Abstract
This proposal introduces an optional strict mode in Python that prevents the accidental overwriting of built-in functions like len, print, max, etc.
This feature will be opt-in and backward-compatible, allowing developers to choose whether to enforce protection against redefining built-in names.
Motivation
Python allows developers to overwrite built-in functions without warnings or errors. While this is sometimes intentional (e.g., mocking in tests), it is often an accidental mistake that leads to unexpected bugs.
For example:
len = 10 # Overwrites the built-in len()
print(len([1, 2, 3])) # TypeError: âintâ object is not callable
In many other languages, reserved words and built-in functions cannot be redefined.
While Python values flexibility, an optional safeguard would help avoid accidental errors.
Rationale
Instead of enforcing this restriction for everyone (which would break existing code),
we introduce a strict mode that developers can enable when they want added protection.
Proposal
Python will introduce a new global flag that prevents overwriting built-in functions when enabled:
sys.strict_builtins
A new flag in the sys module:
import sys
sys.strict_builtins = True # Enables protection against overwriting built-ins
If a user tries to overwrite a built-in function while sys.strict_builtins is True, Python will raise an error:
len = 10 # NameError: âlenâ is a protected built-in function!
By default, sys.strict_builtins = False, ensuring backward compatibility.
strict_mode Module
Alternatively, developers could enable strict mode via a new module:
import strict_mode
strict_mode.enable()
Once activated, attempts to overwrite built-ins would raise an error.
Benefits
Prevents accidental mistakes that can lead to hard-to-debug errors.
Backward-compatible â default behavior remains unchanged.
Explicit opt-in mechanism â developers choose if they want this safeguard.
Easier debugging â avoids common beginner and expert mistakes.
Backward Compatibility
This proposal does not change Pythonâs default behavior. Existing code will continue to work unless strict mode is explicitly enabled.
Discussion
-Should this protection apply only to functions or also to keywords?
-Should it only warn the user instead of raising an error?
-Should the strict_mode module allow fine-grained control (e.g., blocking only specific built-ins)?
Conclusion
This proposal enhances Pythonâs safety by offering an optional mechanism to prevent unintended overwriting of built-in functions.
It allows Python to remain flexible while giving developers a tool to reduce errors and improve code quality.