Is it possible to declare a global variable that is invisible to the importing script?
For example, in script a.py
I have a variable var_a
that is accessible to any function in a.py
. However, in script b.py
that imports a.py
, I want var_a
to be inaccessible.
(A somewhat similar concept to C's static
module variables)
In a.py
:
var_a = "hello"
print("In script a.py:", var_a)
In b.py
:
from a import var_a
print("In script b.py:", var_a)
Testing:
$ python3 b.py
In script a.py: hello
In script b.py: hello
I would like to get an error when referencing var_a
from b.py
.
Is it possible to declare a global variable that is invisible to the importing script?
For example, in script a.py
I have a variable var_a
that is accessible to any function in a.py
. However, in script b.py
that imports a.py
, I want var_a
to be inaccessible.
(A somewhat similar concept to C's static
module variables)
In a.py
:
var_a = "hello"
print("In script a.py:", var_a)
In b.py
:
from a import var_a
print("In script b.py:", var_a)
Testing:
$ python3 b.py
In script a.py: hello
In script b.py: hello
I would like to get an error when referencing var_a
from b.py
.
1 Answer
Reset to default 2Another way also not with a "global" variable: Put the whole module's code in a function so it's in that function's scope, and run and delete that function. Declare as global
the things you do want to offer.
Demo a.py
, with an extra function that can be imported and used:
def scope():
var_a = "hello"
print("In script a.py:", var_a)
global func_a
def func_a():
print("In func_a:", var_a)
scope()
del scope
Now in b.py
you can do this:
from a import func_a
func_a()
But not this:
from a import var_a
print("In script b.py:", var_a)
Attempt This Online!
If you want to assign to the variable inside a function, then declare it nonlocal
. For example:
global func_a
def func_a():
nonlocal var_a
var_a += ' again'
print("In func_a:", var_a)
Attempt This Online!
_var_a
and that tells everyone "don't touch this, and if you do, it's your own fault if anything goes wrong" – juanpa.arrivillaga Commented Mar 7 at 18:50