Last active
February 13, 2017 16:06
-
-
Save jaantollander/93f8718e5703aadeccb86243e7111bc9 to your computer and use it in GitHub Desktop.
Python decorator to add objects to __all__
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def public(f): | |
"""Use a decorator to avoid retyping function/class names. [#]_ | |
* Based on an idea by Duncan Booth: | |
http://groups.google.com/group/comp.lang.python/msg/11cbb03e09611b8a | |
* Improved via a suggestion by Dave Angel: | |
http://groups.google.com/group/comp.lang.python/msg/3d400fb22d8a42e1 | |
References: | |
.. [#] https://stackoverflow.com/questions/6206089/is-it-a-good-practice-to-add-names-to-all-using-a-decorator | |
Args: | |
f (object): Object to be set | |
Returns: | |
object: Decorated object | |
""" | |
all = sys.modules[f.__module__].__dict__.setdefault('__all__', []) | |
if f.__name__ not in all: # Prevent duplicates if run from an IDE. | |
all.append(f.__name__) | |
return f | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment