How to Make a Cross-Module Variable

How to make a cross-module variable?

I don't endorse this solution in any way, shape or form. But if you add a variable to the __builtin__ module, it will be accessible as if a global from any other module that includes __builtin__ -- which is all of them, by default.

a.py contains

print foo

b.py contains

import __builtin__
__builtin__.foo = 1
import a

The result is that "1" is printed.

Edit: The __builtin__ module is available as the local symbol __builtins__ -- that's the reason for the discrepancy between two of these answers. Also note that __builtin__ has been renamed to builtins in python3.

cross module variable

As far as I know, there is no way to import a value from a module and have it readable and writable by the importing scope. When you just import foo in Python, it creates a module object named foo. Getting and setting attributes on a module object will change them in the module's scope. But when you from foo import something, foo is imported and a module object is created, but is not returned. Instead, Python copies the values you specified out of foo and puts them in the local scope. If what you are importing is an immutable type like int or str, then changing it and having the changes reflect in the foo module is impossible. It's similar to this:

>>> class N(object):
... def __init__(self, value):
... self.value = value
>>> n = N(3)
>>> value = n.value
>>> print value, n.value
3 3
>>> value = 4
>>> print value, n.value
4 3

Excepting crude hacks, if you really want to be able to modify the module's variable, you will need to import the module itself and modify the variable on the module. But generally, having to do this is indicative of bad design. If you are the writer of the foo module in question, you may want to look at some other, more Pythonic ways to solve your problem.

Defining cross-module variables with values

I recommend to use a constant instead of a variable:

Module 1

Option Explicit

Public Const MyPath As String = "C:\Temp"

Module 2

Option Explicit

Public Sub ShowPath()
MsgBox MyPath
End Sub

I also recommend to activate Option Explicit: In the VBA editor go to ToolsOptionsRequire Variable Declaration.


If you do it like you did test is empty until it was initialized by running the procedure variablen first. If you use Public Const no initialization is required.

Cross-module variable assigning in python

In the example you give, there is no x ... by the time you get back to try to print it. Its gone out of scope.

You do have some options, one of which is to return it:

foo.py =

def main():
x = 1
return x

And then elsewhere:

import foo
x = foo.main()
print(x)

Access dynamically changing variable across modules

A workaround to this problem is to use for example a global dict. I will show you a code snippet based on the linked question that demonstrates the idea:

file1.py:

global_dict = {'x': 5}
x = 5 # for comparison

file2.py:

from file1 import *

def update_x():
global x
global global_dict
x += 1
global_dict['x'] += 1

main.py:

from file2 import *

update_x()
print(x) # 5
print(global_dict['x']) # 6

Making a variable cross module in Python - Within a class and function

There are lots of different scopes a variable can be bound to, which is what you seem to be confused about. Here are a few:

# a.py
a = 1 # (1) is module scope

class A:
a = 2 # (2) is class scope

def __init__(self, a=3): # (3) is function scope
self.a = a # (4) self.a is object scope

def same_as_class(self):
return self.a == A.a # compare object- and class-scope variables

def same_as_module(self):
return self.a == a # compare object- and module-scope variables

Now see how these different variables (I only called them all a to make the point, please don't do this for real) are named, and how they all have different values:

>>> import a
>>> a.a
1 # module scope (1)
>>> a.A.a
2 # class scope (2)
>>> obj1 = a.A() # note the argument defaults to 3 (3)
>>> obj1.a # and this value is bound to the object-scope variable (4)
3
>>> obj.same_as_class()
False # compare the object and class values (3 != 2)

>>> obj2 = a.A(2) # now create a new object, giving an explicit value for (3)
>>> obj2.same_as_class()
True

Note we can also change any of these values:

>>> obj1.same_as_module()
False
>>> obj1.a = 1
>>> obj1.same_as_module()
True

For reference, your z.py above should probably look like:

import a
n = a.Names()
d.userNames()
d = n.name
print d

because a.Name is a class, but you're trying to refer to an object-scope variable. An object is an instance of a class: I've called my instance n. Now I have an object, I can get at the object-scope variable. This is equivalent to Goranek's answer.

In terms of my previous example, you were trying to access obj1.a without having an obj1 or anything like it. I'm not really sure how to make this clearer, without turning this into an introductory essay on OO and Python's type system.

Python Cross Module Variables

NameVar is not defined in NameAssign; it only exists within NameAssign.NameWorks.InputNames() as a local variable. The easiest way to fix this is to define it in NameAssign at the global level.

Edit:

It turns out that this is what you want to do:

NameResult.py

import NameAssign

namelist = NameAssign.NameWorks(['harry', 'betty', 'sam'])
print namelist.InputNames() # or print(...) for Py3k

NameAssign.py

class NameWorks(object):
def __init__(self, names):
self.names = names

def InputNames(self):
return self.names


Related Topics



Leave a reply



Submit