Search code examples
pythonpython-3.xpython-importpep8

How to correctly call preloader function before imports in Python?


I have config data that should be loaded before another code (because another code use it). So, for now I see only way to do this is to call the function at the top before rest imports:

from Init.Loaders.InitPreLoader import InitPreLoader
# this is my config loader
InitPreLoader.load()

from World.WorldManager import WorldManager
from Init.Loaders.InitLoader import InitLoader
from Init.Registry.InitRegistry import InitRegistry
from Utils.Debug import Logger
# ...
if __name__ == '__main__':
    # ...
    InitLoader.load()

Does it possible to do this in more elegant way and avoid to violate pep8 ?

P.S. If I need to share more code please let me know

UPD: All my classes declared in separate files

This is PreLoader:

from Typings.Abstract.AbstractLoader import AbstractLoader
from Init.Registry.InitRegistry import InitRegistry
from Config.Init.configs import main_config


class InitPreLoader(AbstractLoader):

    @staticmethod
    def load(**kwargs):
        InitRegistry.main_config = main_config

This is Registry (where I store all my initialized data):

from Typings.Abstract.AbstractRegistry import AbstractRegistry


class InitRegistry(AbstractRegistry):

    main_config = None

    login_server = None

    world_server = None

    world_observer = None

    identifier_region_map = None

    region_octree_map = None

Parent of all classes (except AbstractRegistry) is AbstractBase class (it contains mixin):

from abc import ABC

from Config.Mixins.ConfigurableMixin import ConfigurableMixin


class AbstractBase(ConfigurableMixin, ABC):
    pass

This mixin works with main_config from InitRegistry. Also, after PreLoader's load was called, I load rest data with my InitLoader.load() (see first code snapshot):

from Typings.Abstract.AbstractLoader import AbstractLoader
from Init.Registry.InitRegistry import InitRegistry
from Server.Init.servers import login_server, world_server
from World.Observer.Init.observers import world_observer
from World.Region.Init.regions import identifier_region_map, region_octree_map


class InitLoader(AbstractLoader):

    @staticmethod
    def load(**kwargs):
        InitRegistry.login_server = login_server
        InitRegistry.world_server = world_server
        InitRegistry.world_observer = world_observer
        InitRegistry.identifier_region_map = identifier_region_map
        InitRegistry.region_octree_map = region_octree_map

Solution

  • Well, for now I have found solution: I moved from Init.Loaders.InitPreLoader import InitPreLoader to separate file and called InitPreLoader.load() there. But I not like this solution, because my PyCharm IDE highlights it as unused import:

    import Init.Init.preloader
    from World.WorldManager import WorldManager
    # ...
    

    Maybe it is possible to improve this solution ? Or maybe another (more elegant) solition exists ?