How to import a large number of global variables without listing each of them? (Python)

DEFINE1 = 1
DEFINE2 = 2
DEFINE3 = 3
...
DEFINE10 = 10

Let's say one file has 10 global constants that I want to import into another file.

Instead of doing the following, is there an easier way to import all global constants without doing something like: from file_one.py import *. I do not want it to import the entire file, only global variables.

from file_one.py import DEFINE1, DEFINE2, DEFINE3, ..............
+5
source share
5 answers

, , , , constants.py, from constants import * - . , , , , SOME_CONSTANT.

, , , . - ,

import re, file_one
for name,val in file_one.__dict__.items():
    if re.match("[A-Z0-9_]+", name):
        globals()[name] = val

, , , .

+4

, :

import file_one
g = globals()
for key in dir(file_one):
    if key.isupper():
        g[key] = getattr(file_one, key)

:

import file_one
globals().update((key, getattr(file_one, key)) for key in dir(file_one)
                                               if key.isupper())

: . , . from constants import *.

+4

:

from file_constants import *

..

0

, . , - :

# file_one.py
class _COLORS:
    BLUE = 0
    RED = 1
    GREEN = 2
COLORS = _COLORS()

:

# file_two.py
from file_one import COLORS
print COLORS.BLUE #prints 0
0

:

class _Constants(object): pass

constants = _Constants()
constants.DEFINE1 = 1
constants.DEFINE2 = 2
...

, , ( ".py" ):

from file_one import constants

:

colors = _Constants()
colors.RED = (255,0,0)
colors.GREEN = (0,255,0)
colors.BLACK = (0,0,0)
colors.WHITE = (255,255,255)

linetypes = _Constants()
linetypes.SOLID = 0
linetypes.DOTTED = 1
linetypes.DASHED = 2

. - , .

0

All Articles