-Поиск по дневнику

Поиск сообщений в rss_planet_mozilla

 -Подписка по e-mail

 

 -Постоянные читатели

 -Статистика

Статистика LiveInternet.ru: показано количество хитов и посетителей
Создан: 19.06.2007
Записей:
Комментариев:
Написано: 7


Matthew Ruttley: Avoiding multiple reads with top-level imports

Пятница, 02 Декабря 2016 г. 03:10 + в цитатник

Recently I’ve been working with various applications that require importing large JSON definition files which detail complex application settings. Often, these files are required by multiple auxiliary modules in the codebase. All principles of software engineering point towards importing this sort of file only once, regardless of how many secondary modules it is used in.

My instinctive approach to this would be to have a main handler module read in the file and then pass its contents as a class initialization argument:

# main_handler.py

import json

from module1 import Class1
from module2 import Class2

with open("settings.json") as f:
    settings = json.load(f)

init1 = Class1(settings=settings)
init2 = Class2(settings=settings)

The problem with this is that if you have an elaborate import process, and multiple files to import, it could start to look messy. I recently discovered that this multiple initialization argument approach isn’t actually necessary.

In Python, you can actually import the same settings loader module in the two auxiliary modules (module1 and module2), and python will only load it once:

# main_handler.py

from module1 import Class1
from module2 import Class2

init1 = Class1()
init2 = Class2()

# module1.py

import settings_loader

class Class1:
    def __init__(self):
        self.settings = settings_loader.settings

# module2.py

import settings_loader

class Class2:
    def __init__(self):
        self.settings = settings_loader.settings

# settings_loader.py

import json

with open("settings.json") as f:
    print "Loading the settings file!"
    settings = json.load(f)

Now when we test this out in the terminal:

MRMAC:importtesting mruttley$
MRMAC:importtesting mruttley$
MRMAC:importtesting mruttley$ python main_handler.py
Loading the settings file!
MRMAC:importtesting mruttley$

Despite calling

import settings_loader
  twice, Python actually only called it once. This is extremely useful but also could cause headaches if you actually wanted to import the file twice. If so, then I would include the settings importer inside the
__init__()
  of each ClassX and instantiate it twice.

http://ikigomu.com/?p=323


 

Добавить комментарий:
Текст комментария: смайлики

Проверка орфографии: (найти ошибки)

Прикрепить картинку:

 Переводить URL в ссылку
 Подписаться на комментарии
 Подписать картинку