EcSync
EcSync

Reputation: 860

How can I call on a variable within a function, from outside of that function?

I realise this may be marked as a duplicate however no others are specific to my problem. I have variables within various functions which i need to call separately. I get the error function pos has no 'stn' member

I have tried using a global var however is a bit of a bodge and isn't the neatest...

def pos():
    stn = int((latest))
pos()

with open('current_data.json', 'w') as outfile:
    data['data'].append({
    'lineone': pos.stn,
    }
)

I am expecting these variables to be written to a json (i have not included jso n imports and file set up as it is not relevant to the issue)...however i just get this error Function 'pos' has no 'stn' member; maybe 'stn_other'? where stn_other is another variable from the pos function. I would appreciate the help.

Upvotes: 0

Views: 64

Answers (3)

buran
buran

Reputation: 14253

you need to return the result you want to from pos() function. Not that I would recommend writing a function for conversion to int - it just adds overhead to available built-in function:

import json 

latest = '10'

def pos(latest):
    stn = int(latest)
    return stn

json_data = {'data':[]} # this is something you have in advance
json_data['data'].append(pos(latest))  

with open('current_data.json', 'w') as outfile:
    json.dump(json_data, outfile, indent=4)

resulting current_data.json

{
    "data": [
        10
    ]
}

Upvotes: 1

BoarGules
BoarGules

Reputation: 16941

If you assign a value to a local variable inside a function, it disappears when the function returns. But you want it to persist. So it seems to me that you want pos to be an instance of a class, not a function. When you do pos.stn that is certainly what it looks like.

class Pos:
    def __init__(self, latest='0'):
        self.stn = int(latest)      

Then when you make an instance of the class, like this

>>> pos = Pos()

the data persists inside pos:

>>> print (pos.stn)
0

Upvotes: 1

meowgoesthedog
meowgoesthedog

Reputation: 15035

Although this is generally bad practice, you need to make stn an attribute of the function object pos:

def pos():
    pos.stn = int((latest))

Otherwise when pos returns, stn would go out of scope and be marked for garbage collection.

Upvotes: 1

Related Questions