Create all global variables

I have a function in my Python script where several variables are created, and I want to use them in other functions. I was thinking about using global for this, but I was thinking that this would be the wrong way to do this.

So can someone tell me what would be the best way to create variables in a function for other functions?

+6
source share
4 answers

Organize variables in class . Create an instance of the class in one function, and then pass the instance to where you need it.

Rule of thumb: if something global seems like a good solution at some point, don’t do it. There is always a better way.

+8
source

You can create a namespace object β€” an object that functions as a namespace to preserve the global namespace:

 class namespace(): pass global_data=namespace() def add_attributes(obj): obj.foo="bar" add_attributes(global_data) print (global_data.foo) #prints "bar" 

However, this is only slightly better than using the global keyword. You really want a class here, as Paul mentioned.

+2
source

Declare variables as function attributes.

 def f1(): f1.a=100 f2.b=200 def f2(): print(f1.a,f2.b) f1() f2() 

exit:

 100 200 
+2
source

This can be a good place to implement a class. This has many advantages. See Classes in textbooks .

+1
source

Source: https://habr.com/ru/post/916791/


All Articles