How to make user config available to all classes of a module

I am writing a Python library designed to be used as a third party library.

great_library/__init__.py

:

class ClassA(object):

    @cache()
    def foo(self):
        pass

class ClassB(object):

    @cache()
    def bar(self):
        pass

class GreatLibrary(object):

    @classmethod        
    def great_api(cls):
        pass

    # uses ClassA and ClassB

      

this library is used like:

from great_library import GreatLibrary
GreatLibrary.great_api()

      

Now the problem is that I would like the user to expire the config cache. which should be passed to @cache()

:@cache(seconds)

How do I create a module structure like this so that the user can easily navigate to the config and let it be used by classes A and classB? thank

+3


source to share


1 answer


The main problem is that the variable passed to the decorator will be read when the module is loaded. So there is no way to change it before (at least unless you want to reload the module by some kind of hack, but cannot change old objects). So you need a hook where the great_library

cache time value can get and where the user can write the desired value.

A simpler and more widely used method is setting environment variables. At the top of your module, great_library

you can check the variables and load the default cache time:

import os
default_time = os.getenv("GREAT_LIBRARY_CACHE_TIME", None)

      

In your code, use @cache(default_time)

. I'm not sure if the API cache()

takes a value None

as a default argument, otherwise just change the receipt to adapt it to your problem.



Users great_library

can now install it either at os.putenv()

the devolopment stage (before importing the module) or in the OS environment during production.

Another way to put the hook is to use the configuration module to import. IMHO this method can only be useful if you have a set of properties to set. If you follow this path, your module great_library

should implement some of this:

try:
    from great_library_config import *
except ImportError:
    # Default configurations like...
    default_time = None

      

Personally, I try to avoid such module solutions, but it can be useful for highly configurable applications or frameworks. Anyway, in this case the user can use the config module for production and override it during development / testing.

+1


source







All Articles