Python中如何禁止函数使用全局变量?限制函数仅访问局部与传入参数
Great question! Yes, it's totally possible to lock down a Python function so it can only access its own local variables and incoming parameters—no sneaky global variable access allowed. Let's break down how to make this work with your example scenario.
First, let's define the baseline code you're working with (to set context):
a = "global variable" def my_fun(x): print(x) # Should work (it's a parameter) print(a) # Should throw an error (it's a global variable) my_fun("local parameter")
Normally, this would print both the parameter and the global a. We want to modify this so print(a) raises a NameError.
Method 1: Use exec() with an Empty Global Namespace
The cleanest way to isolate the function's scope is to define it using exec() and pass an empty dictionary as the global scope. This cuts off the function's access to your script's actual global variables.
Here's how to implement it:
a = "global variable" # Define the function inside exec with a restricted global scope exec(""" def my_fun(x): print(x) print(a) """, {}) # Empty dict = no access to outer global variables try: my_fun("local parameter") except NameError as e: print(f"Error as expected: {e}") # Output: Error as expected: name 'a' is not defined
How it works:
When you pass {} as the second argument to exec(), the function my_fun is created in a sandboxed environment where the global namespace is empty. The parameter x still works because it's part of the function's local scope, but a can't be found anywhere—hence the error you want.
Method 2: Override the Function's __globals__ Attribute
If you already have a function defined and want to retroactively restrict its scope, you can directly override its __globals__ attribute to an empty dictionary. This is a bit of a hack, but it gets the job done:
import types a = "global variable" def my_fun(x): print(x) print(a) # Cut off access to global variables by resetting __globals__ my_fun.__globals__ = {} try: my_fun("local parameter") except NameError as e: print(f"Error as expected: {e}")
Bonus: Restrict Built-in Functions Too
Wait, a quick note: By default, even an empty global dictionary in Python includes access to built-in functions like print(). If you want to restrict those too (or whitelist only specific ones), you can explicitly define __builtins__ in your global namespace:
exec(""" def my_fun(x): print(x) print(a) """, {"__builtins__": {"print": print}}) # Only allow the print() built-in
This way, the function can only use the built-ins you explicitly approve.
Key Takeaways
- Isolating a function's scope to only local variables and parameters is absolutely feasible in Python.
- The
exec()approach with a controlled global namespace is the most reliable and readable method for this use case. - Be cautious with overriding
__globals__—it's not officially supported in all Python versions, but works in most modern implementations.
内容的提问来源于stack exchange,提问作者Tautvydas

