开发者

Modifying module globals using externally defined function

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 开发者_JS百科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 AllList decorator:

class AllList(list):
    """list which can be called in order to be used as a __all__-adding decorator"""
    def __call__(self, obj):
        """for decorators"""
        self.append(obj.__name__)
        return obj 

Import it from whereever, and at the top of your module have

__all__ = whereever.AllList()

then in your module it looks like

@__all__
def some_func():
...

@__all__
def another_func():
...

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜