Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making all variables global

I have a function in my Python script where multiple variables are created, and I want to use them in other functions. I thought of using global for this but I thought it would be the incorrect way to do so.

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

like image 282
Markum Avatar asked May 27 '12 16:05

Markum


People also ask

Is it a good idea to declare your variables globally?

Using global variables causes very tight coupling of code. Using global variables causes namespace pollution. This may lead to unnecessarily reassigning a global value. Testing in programs using global variables can be a huge pain as it is difficult to decouple them when testing.

How do you make all global variables in python?

Python globals() The globals() method returns a dictionary with all the global variables and symbols for the current program.

Is it better to use more number of global variables?

The value of a global variable can be changed accidently as it can be used by any function in the program. If we use a large number of global variables, then there is a high chance of error generation in the program.

Is everything global in python?

What are the rules for local and global variables in Python? ¶ In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a value anywhere within the function's body, it's assumed to be a local unless explicitly declared as global.


2 Answers

Organize the variables into a class. Instantiate the class in one function and then pass the instance to wherever you need it.

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

like image 79
Paul Sasik Avatar answered Oct 31 '22 03:10

Paul Sasik


You could create a "namespace" object -- an object which functions as a namespace for the purpose of keeping your global namespace clear:

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 marginally better than using the global keyword. You really do want a class here as mentioned by Paul.

like image 30
mgilson Avatar answered Oct 31 '22 05:10

mgilson