简体   繁体   中英

Most Pythonic way to use a variable from one script in a second object

What's a good way to use a variable from one script inside the object in another file? I thought using global would work but it does not.

My config loading class has an expensive disk operation that loads the config file from disk into a dictionary. So naturally I want to avoid repeating this operation every time I need the config variables; I want to keep it in memory for all the other objects to use.

This works, but is kludgy. Aside from battery.py I have other classes not shown and need to pass config as a parameter for all.

main.py:

#!/usr/bin/python
from config import CONFIG
from battery import BATTERY
config = CONFIG().config
battery = BATTERY(config)
print("Running this the first time.")
battery.print_config()
print("Running again. Should not go slow.")
battery.print_config()

config.py:

class CONFIG(object):
    def __init__(self):
        # Simulating the expensive disk operation
        from time import sleep
        for i in range(1, 4):
            print i
            sleep(1)

        self.config = {'parameter': 'value'}

battery.py

class BATTERY(object):
    def __init__(self, config):
        self.config = config

    def print_config(self):
        print(self.config['parameter'])

Result:

$ ./main.py
1
2
3
Running this the first time.
value
Running again. Should not go slow.
value

I thought I might try to global config inside battery.py's init but that fails with the error below.

class BATTERY(object):
    def __init__(self): # Removed the config argument
        # Added global config
        global config
        self.config = config

    def print_config(self):
        print(self.config['parameter'])

Result:

$ ./main.py
Traceback (most recent call last):
  File "./main.py", line 5, in <module>
    battery = BATTERY()
  File "/cygdrive/c/Users/nbktvlh/Desktop/Test/battery.py", line 4, in __init__
    self.config = config
NameError: global name 'config' is not defined

This works but makes it more tightly coupled. (Right?) And strangely, it executes the print twice.

class BATTERY(object):
    def __init__(self):
        # Added this line
        from main import config
        self.config = config

    def print_config(self):
        print(self.config['parameter'])

Result:

$ ./main.py
1
2
3
1
2
3
Running this the first time.
value
Running again. Should not go slow.
value
Running this the first time.
value
Running again. Should not go slow.
value

Maybe there's a better way to do this?

Thanks to @juanpa.arrivillaga for the answer. I shouldn't make config a class.

main.py:

#!/usr/bin/python
from config import config
from battery import BATTERY
battery = BATTERY()
print("Running this the first time.")
battery.print_config()
print("Running again. Should not go slow.")
battery.print_config()

config.py:

# Simulating the expensive disk operation
from time import sleep
for i in range(1, 4):
    print i
    sleep(1)

config = {'parameter': 'value'}

battery.py:

class BATTERY(object):
    def __init__(self):
        from config import config
        self.config = config

    def print_config(self):
        print(self.config['parameter'])

Results:

$ ./main.py
1
2
3
Running this the first time.
value
Running again. Should not go slow.
value

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM