user5827844
user5827844

Reputation:

How can I have a variable's value be a method, and have a method use that variable in Python 2.7?

I want to have a variable have the value of a method, so when I run the variable I run a method. This only works if I create the variable after the method. However, I also want to use that variable in the same method it runs. That only works if I create the variable before the method.

def test():
    testing()

def testing():
    print "hello"
    var

var = test()
var

So when I run this program, it tells me "global name 'var' is not defined." And if I create the variable before the method like so,

var = test()

def test():
    testing()

def testing():
    print "hello"
    var

var

it tells me "name 'test' is not defined"

I do mean function when I say method. And when I say run the method, I am referring to the line that says 'var'

What I am asking is how can I have a variable's value be the name of a method, and have that variable be used in another method.

Upvotes: 0

Views: 114

Answers (1)

Ben
Ben

Reputation: 71495

With the line:

var = test()

you're not actually assigning the function test to the variable var. You're assigning the expression test(). The parentheses after test mean you're calling the function test, and the expression is the value resulting from that call. That's what you're assigning to var.

Because this call occurs in the assignment statement that creates var, it has to be carried out before var actually exists. So when test calls testing, testing tries to access var, which doesn't exist yet. That's your error.

What you need to do instead is to just assign the function test directly to var, without calling it:

var = test

This leaves var bound to the function. Note that to use this, you have to use parentheses to actually call it, so you need var() on the next line, not just var.

Note that test itself is just an ordinary variable that happens to be bound to a function. The def statement basically just creates a function object, sets that function object's __name__ value to "test", and binds the variable test, all at the same time.

If in your real use case, you need to pass some arguments to test and you don't want to have to know about those when you call var, then what you instead want to do is create a zero-argument wrapper function that calls test when it is called, like this:

def var():
    return test(some, arguments, here)

You can do that as a local definition in a function just fine, it doesn't have to be created separately at module scope. Alternatively, you could create a nameless lambda function, which you can do as an expression rather than needing a separate definition:

var = lambda: test(some, arguments, here)

But you'll still always need to use parentheses to call var, like var(); you'll never be able to call it by just writing var.

Upvotes: 2

Related Questions