3

I have

# file1.py
global a, b, c, d, e, f, g

def useful1():
   # a lot of things that uses a, b, c, d, e, f, g

def useful2():
   useful1()
   # a lot of things that uses a, b, c, d, e, f, g

def bonjour():
   # a lot of things that uses a, b, c, d, e, f, g
   useful2()

and

# main.py   (main file)
import file1

# here I would like to set the value of a, b, c, d, e, f, g  of file1 !

bonjour()

How to deal with all these global variables ?

PS : I don't want to add a, b, c, d, e, f, g for ALL functions, it would be very redundant to have to do :

def useful1(a, b, c, d, e, f, g):
...
def useful2(a, b, c, d, e, f, g):
...
def bonjour(a, b, c, d, e, f, g):
...
2
  • I don't think it's possible, since those global variables only exist inside the file. Commented Dec 6, 2013 at 9:07
  • 3
    I'm a little confused here. What exactly do you expect your global statement to be doing? global at the top-level of a file is an effectively useless statement. global only has meaning for identifiers inside a function... Commented Dec 6, 2013 at 9:09

3 Answers 3

9

You don't need to pass them. If you've done import file1 at the top of main.py, you can just refer to file1.a etc directly.

However, having this many global variables smells very bad. You probably should refactor using a class.

Sign up to request clarification or add additional context in comments.

Comments

2

The canonical way to share information across modules within a single program is to create a special module (often called config or cfg). Just import the config module in all modules of your application; the module then becomes available as a global name. Because there is only one instance of each module, any changes made to the module object get reflected everywhere. For example:

config.py:

x = 0   # Default value of the 'x' configuration setting

mod.py:

import config
config.x = 1

main.py:

import config
import mod
print config.x

Comments

1

Use a dict to wrap those global variable, then only one param for functions

1 Comment

thank you. can you give just a simple example in this context with dict?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.