3

I am writing in caller script:

from XXX import config

....

config.limit = limit
data.load_data()

where config.py has

limit = None

inside and data.py has

from .config import *
...
def load_data():
    ...
    if limit is not None:
        limit_data(limit)

I was expecting everybody is refering the same varibale limit in config.py module. Unfortunately, I see while debygging, that load_data sees None limit, despite the fact it was set before.

Why?

1 Answer 1

4

When you do from .config import *, you are importing a copy of limit from config into your own namespace. The limit entity that resides in config is not the same as the one you import. They reside in their own respective namespaces and are independent of each other.

As a workaround for this, consider this example:

A.py

foo = 5

def print_foo():
    print(foo)

B.py

import A

A.foo = 10
A.print_foo()

Now, running B.py should give:

$ python B.py
10

Meaning, you can refer to the same variable by prepending the namespace qualifier.

For relative imports, you'd do something similar:

app/
    __init__.py
    A.py
    B.py

In B.py, you'd call import app.A. You'd then refer to the variable as app.A.limit.

Sign up to request clarification or add additional context in comments.

5 Comments

How to have one? Or how to refer one?
You'll change from .config import * to import .config. Then, if I'm not mistaken, referring to config.limit will refer to the same item.
@Dims Added an example.
Neither import config, nor import .config works. First complains "no module config", second complains "Invalid syntax"
@Dims Edited my answer. That should help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.