Hello all,
A bit of a funky one. Imagine I have a module b
, in which a function func
is defined that references a variable var
not defined in b
. I then import func
into a module a
- where var
is defined - and run it. The interpreter complains that var
is not defined.
I’ve seen it suggested elsewhere that this would be poor practice anyway, as it means b
relies on the existence of something external, and a better way would be to pass var
into func
when it’s called from a
One problem with that approach, as far as I see it, is that if func
contains other nested function calls that also need access to the content of var
, it has to be written in such a way that it passes it through to those as well, and they need to pass it into any nested calls they might contain (should there be a need).
This makes b
’s code more confusing than it needs to be, as one has to constantly follow var
as it’s passed through. It would be simpler if var
could be defined in a
and then anything called from within a
could read it’s value without requiring it to be passed in.
My programming knowledge is still pretty shallow, but I’m guessing it’s something to do with the fact that there is a separate name-space for each module, so when a function defined in b
is called from a
, names are still resolved using b
’s name-space - not a
’s (feel free to correct if this isn’t the case).
The obvious answer is to define func
in a
and do away with b
altogether, but for my purpose a
isn’t really another module but an interactive interpreter session that I’m using to test b
, and I can’t really define var
in b
as var
’s contents are created at runtime.
a couple of examples…
content of b.py
def func():
print(var)
content of a.py
from b import func
var = 'foo'
func()
*Interpreter complains
It can be achieved as follows but I think it makes b.py kind of messy…
content of b.py
def funcOne(arg):
funcTwo(arg)
def funcTwo(arg):
funcThree(arg)
def funcThree(arg):
print(arg)
content of a.py
from b import func
var = 'foo'
funcOne(foo)
Is this just how a module has to be written if it’s going to have it’s contents imported and used elsewhere?