jf192210
jf192210

Reputation: 157

Updating an Imported Object

Suppose file_A.py is written as so:

#file_A.py

my_object = create_new_object()

def update_object():
    global my_object
    my_object = update(my_object)

and then in file_B.py we do as so:

#file_B.py

from file_A import my_object, update_object

def process_object(object):
    #do some operation ...


process_object(my_object) #first call to process_object()
update_object()
process_object(my_object) #second call to process_object()

My question is, when the second call to process_object() is made, will it use the original version of my_object ,which is imported at the top of file_B.py, be used, or will it use the updated version which replaces my_object when the update_object() function is called from file_B.py?

Upvotes: 2

Views: 331

Answers (2)

Nicholas Obert
Nicholas Obert

Reputation: 1628

Note that the same variable (even if global) can have different values in different python modules. Thus the best way to reference a variable from another module is by using module.variable So your code might look like

import file_A

print(file_A.my_object)
file_A.process_object(file_A.my_object)
file_A.process_object(file_A.my_object)
print(file_A.my_object)

The key to referencing the right variable is to use the module name. This can also be useful when you are working with multiple files and you need to keep some global variables.

Upvotes: 1

flakes
flakes

Reputation: 23644

Variables are passed by reference. In file_A you will update the modules reference to my_object but the value imported in file_B will still have the old reference. For example:

Say I have file testA.py

a = 1
def foo():
    global a
    a = 2

And testB.py

from testA import a, foo

print(a)
foo()
print(a)

If I run testB.py you will get the output 1,1

This is because the global only updated the reference attached to the module testA.py. If you were to access the module however, then you would see it did update there. An example where you access the module instead

testC.py

import testA

print(testA.a)
testA.foo()
print(testA.a)

This will output 1, 2

Upvotes: 2

Related Questions