1

How i can use and edit global vars in any place of my module? My project looks like

project/
---- models/
---- ---- first.py
---- ---- second.py
---- run.py

Run.py is main and i use it ti start app, global vars init in it.

1 Answer 1

2

You would have to import them into any other module that you want to use them in. Global variables are only global to the file they're in (unless imported elsewhere).

Note that if you want changes to propagate outside the module you import into, you need to do one of two things:

  • Use the non-from import syntax (e.g. import foo.bar and then foo.bar = <value>)
  • Use a mutable type and modify it in-place (e.g. a dictionary)

The reason for this is that if you use a from import, it creates a local version of the variable that is independent of the one from the other module, but has the same value. For mutable types, this value is a reference, and thus as long as you modify the object in-place, the changes will be visible everywhere (because all the references will point to the same object).

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

4 Comments

when i import run.var in first and edit it, in second there are no result
What's the type of run.var? How are you importing it? (Are you using import run.var or from run import var?) If you're using from ... import ..., try switching to import run.var and then run.var = ....
from run import var and var = " "
That's your problem, then - when you use from run import var you're just getting a copy of the value in a new local variable called var - if you want changes to propagate across all instances, you need to either import and work with the original version (import run.var) or use a reference type (such as a dictionary or a list) and just modify that item without overwriting it.

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.