Reputation: 2787
I want a function to be run as if it was written in the main program, i.e. all the variables defined therein can be accessed from the main program. I don't know if there's a way to do that, but I thought a wrapper that gives this behaviour would be cool. It's just hacky and I don't know how to start writing it.
Upvotes: 0
Views: 88
Reputation: 77892
I have pieces of code written inside functions, and I really want to run them and have all the variables defined therein after run without having to write the lengthy return statements. How can I do that?
That's what classes are for. Write a class with all your functions as methods, and use instance attributes to store the shared state. Problem solved, no global required.
Upvotes: 1
Reputation: 557
Define your variables in the global scope and access them inside the function with the global keyword, like so:
x=99
def fn():
global x
x=100
fn()
print(x) # 100
That been said, I agree with @juanpa.arrivillaga, this may not be the best way to do it.
Upvotes: 0