Tetrikus
Posts: 28
Joined: Tue Apr 05, 2016 5:42 am

How to deliver variable to a function in another file which then uses the variable value

Sat Aug 25, 2018 6:43 am

Often, when I try to write something in python, I don't understand this, allthough it must be a very basic question. When I define a variable in the file function.py and then call a function my_function, how can I manage to use the variables value instead of its name?

function.py

Code: Select all

ch1 = 0x80

def my_function(channel, value):
    print(channel)
    print(value)
call.py

Code: Select all

my_function(ch1, 100)
print(channel) does output ch1, but I like to use the variable value of ch1 instead. How would I do that?

DirkS
Posts: 9956
Joined: Tue Jun 19, 2012 9:46 pm
Location: Essex, UK

Re: How to deliver variable to a function in another file which then uses the variable value

Sat Aug 25, 2018 12:57 pm

Can you elaborate a bit more...

Do you import function.py in call.py? Please post *full* programs. There is no link between the scripts atm.
And can you post the literal output instead of just a description of that output?
And also of what you want as output.

robbes
Posts: 144
Joined: Sun Jan 20, 2013 7:11 pm
Location: Canada - off the west coast

Re: How to deliver variable to a function in another file which then uses the variable value

Sun Aug 26, 2018 4:00 am

It isn't possible to access a variable name directly in python - the name is a mapping, not an object.
You could create a string with the same variable name as follows, though :

Code: Select all

ch1_name = [ k for k, v in locals().items() if v == ch1][0]
print(ch1_name, ch1)
But I would personally just create an additional variable

Code: Select all

ch1_name = 'ch1'
and use that.

Return to “Python”