List and use the variables defined inside my own function

Tags: ,

Suppose that I have a function like this one:

def foo():
    a = 1
    b = 2
    c = 3

    return c

Now can I use the a, bvariables? Even if foo() is not returning them like this?

foo().a + foo().b

I know this is easy to do if foo was a class, but it’s not.


Even though you are saying you have a function, not a class, python is able to transcend those differences using callable classes. Those are normal classes whose instances can be called as normal functions while still maintaining an internal state. Here is a demonstration:

class Foo:
    def __init__(self):
        self.a = self.b = self.c = None

    def __call__(self): 
        self.a = 1
        self.b = 2
        self.c = 3
        return self.c

foo = Foo()
print(foo()) # will print 3
print(foo.a) # will print 1
print(foo.b) # will print 2

In the above code snippet, you can think of Foo as a class that generates objects (int this case foo), each being a function. Your code can call foo() and what this will do, is execute the __call__() method of that class. Since however __call__() uses self.a, self.b, self.c instead of local variables a, b, c, their values after the execution of the function will be saved inside the foo object. So you can check them just by doing foo.a and so on.

If you would like to add more arguments in your original foo() function, simply add them to the __call__() method and assign values to them when calling foo().

Source: stackoverflow