I have a very simple decorator function I use to expose functions defined in a module via the module’s __all__ property. Because I use it for multiple modules within a package, I have it defined in the package’s __init__.py.
Because I cannot use __all__ from within the definition, as it would refer to the __all__ of the __init__.py module (or rather the package), I am currently doing it like this:
def expose ( fn ):
fn.__globals__['__all__'].append( fn.__name__ )
This seems to work totally fine. However I’m not sure if using the __global__ property is the ideal way to do it, especially as that property seems to be undocumented (at least I couldn’t find anything about it in the documentation).
Is using __globals__ fine for that, or is there maybe an easier and more robust way to make this work?
edit:
For clarification, I don’t necessarily need to access the __all__ property of the module. I can easily use a different name and end up with the same question. I’m just using __all__ because its purpose of holding all exposed objects in a module matches my intention. But at the same time I could also name it exposedFunctions or whatever. So the question is more about how to access the global properties of the module.
You might like Thomas Rachel’s
AllListdecorator:Import it from whereever, and at the top of your module have
then in your module it looks like
and no need to worry about globals.
Update
If you really want to worry about globals, take a look at Use a class in the context of a different module — it is not pretty, however.