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.