import updated variable data from another script in python

Question:

test.py

asd = ''

def upd():
    asd = 'Anything'

def hello():
    upd()
    print('hello')
    return asd

script.py

import test as tt

print(tt.hello())

how can i get updated ‘asd’ value in script.py ?
anyone please suggest

Asked By: KLAS R

||

Answers:

Try this

In test.py

asd = ''
def upd():
    return 'Anything'
def hello():
    asd=upd()
    print('hello')
    return asd

In script.py

import test as tt
asd=tt.hello()
print(asd)
Answered By: Xor_ia

You didn’t update anything. upd created a new local variable that was discarded after the call returned.

If you mean for upd to update the global variable asd, you need to declare the name as global first.

asd = ''

def upd():
    global asd
    asd = 'Anything'

def hello():
    upd()
    print('hello')

Now, after calling tt.hello, you can access tt.asd like any other module attribute.

import test as tt
tt.hello()
print(tt.asd)

(I am intentionally ignoring the issue of whether a function should be mutating the global variable asd. There are reasonable use cases for doing so, and not enough context in the question to make any such judgement in this case.)

Answered By: chepner