Categories
Python Answers

How to access a function variable outside the function without using “global” with Python?

Spread the love

Sometimes, we want to access a function variable outside the function without using "global" with Python.

In this article, we’ll look at how to access a function variable outside the function without using "global" with Python.

How to access a function variable outside the function without using "global" with Python?

To access a function variable outside the function without using "global" with Python, we can add an attribute to the function.

For instance, we write

def hi():
    # ...
    hi.bye = 100
    sigh = 10

hi()
print(hi.bye)

to add the bye attribute to the hi function.

We can do this since functions are objects in Python.

And then we get the value with hi.bye.

Conclusion

To access a function variable outside the function without using "global" with Python, we can add an attribute to the function.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *