Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing global variables to another file in Python?

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):
...
like image 640
Basj Avatar asked Jul 20 '26 04:07

Basj


1 Answers

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.

like image 188
Daniel Roseman Avatar answered Jul 21 '26 18:07

Daniel Roseman