Global Variable from a Different File Python

Global Variable from a different file Python

Importing file2 in file1.py makes the global (i.e., module level) names bound in file2 available to following code in file1 -- the only such name is SomeClass. It does not do the reverse: names defined in file1 are not made available to code in file2 when file1 imports file2. This would be the case even if you imported the right way (import file2, as @nate correctly recommends) rather than in the horrible, horrible way you're doing it (if everybody under the Sun forgot the very existence of the construct from ... import *, life would be so much better for everybody).

Apparently you want to make global names defined in file1 available to code in file2 and vice versa. This is known as a "cyclical dependency" and is a terrible idea (in Python, or anywhere else for that matter).

So, rather than showing you the incredibly fragile, often unmaintainable hacks to achieve (some semblance of) a cyclical dependency in Python, I'd much rather discuss the many excellent way in which you can avoid such terrible structure.

For example, you could put global names that need to be available to both modules in a third module (e.g. file3.py, to continue your naming streak;-) and import that third module into each of the other two (import file3 in both file1 and file2, and then use file3.foo etc, that is, qualified names, for the purpose of accessing or setting those global names from either or both of the other modules, not barenames).

Of course, more and more specific help could be offered if you clarified (by editing your Q) exactly why you think you need a cyclical dependency (just one easy prediction: no matter what makes you think you need a cyclical dependency, you're wrong;-).

Using global variables between files?

The problem is you defined myList from main.py, but subfile.py needs to use it. Here is a clean way to solve this problem: move all globals to a file, I call this file settings.py. This file is responsible for defining globals and initializing them:

# settings.py

def init():
global myList
myList = []

Next, your subfile can import globals:

# subfile.py

import settings

def stuff():
settings.myList.append('hey')

Note that subfile does not call init()— that task belongs to main.py:

# main.py

import settings
import subfile

settings.init() # Call only once
subfile.stuff() # Do stuff with global var
print settings.myList[0] # Check the result

This way, you achieve your objective while avoid initializing global variables more than once.

Python: change global variable from within another file

All that from config import ADDRESS, change_address does is take ADDRESS and change_address from your config module's namespace and dumps it into your current module's name-space. Now, if you reassign the value of ADDRESS in config's namespace, it won't be seen by the current module - that's how name-spaces work. It is like doing the following:

>>> some_namespace = {'a':1}
>>> globals().update(some_namespace)
>>> a
1
>>> some_namespace
{'a': 1}
>>> some_namespace['a'] = 99
>>> a
1
>>> some_namespace
{'a': 99}

The simplest solution? Don't clobber name-spaces:

import config
config.change_address("192.168.10.100")
print("new address " + config.ADDRESS)

Access variable from a different function from another file

You can access the value of a variable in a function by 1) returning the value in the function, 2) use a global variable in the module, or 3) define a class.

If only want to access a single variable local to a function then the function should return that value. A benefit of the class definition is that you may define as many variables as you need to access.

1. Return value

def champs_info(champname:str, tier_str:int):  
...
tier = tier_access.text
return tier

2. global

tier = None
def champs_info(champname:str, tier_str:int):
global tier
...
tier = tier_access.text

Global tier vairable is accessed.

from mypythonlib import myfunctions

def test_champs_info():
myfunctions.champs_info("abomination", 6)
return myfunctions.tier

print(test_champs_info())

3. class definition:

class Champ:
def __init__(self):
self.tier = None
def champs_info(self, champname:str, tier_str:int):
...
self.tier = tier_access.text

test_functions.py can call champs_info() in this manner.

from mypythonlib import myfunctions

def test_champs_info():
info = myfunctions.Champ()
info.champs_info("abomination", 6)
return info.tier

print(test_champs_info())

global variable not changing from various different files

When declared in function, global running creates a new running variable that overrides the imported running. What you want to do here is nonlocal running.

Also, this is typically why global is never recommended. You could achieve the same kind of behavior more securely using a singleton class ; or just import file1 (in file2) then test on file1.running.

The global variable from a function() within a different .py file isnt being found within Python script?

As per the advice from the comments:

  • I wrote the function call as func.enter_name()
  • Set 'global myName' within the enter_name() function
  • Used 'func.myName' when importing the variable


Related Topics



Leave a reply



Submit