Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically exporting all functions (vs manually specifying __all__)

Tags:

python

I have a helpers.py file which defines about 30 helper functions to be exported as follows:

from helpers import *

To be able to do this, I have added all 30 functions to the __all__ variable. Can I automatically have all functions exported, rather than having to specify each one?

like image 285
Randomblue Avatar asked Jan 16 '12 14:01

Randomblue


3 Answers

Actually I think Gandaro is right, you don't have to specify __all__, but if, for some unknown reason, you would have to do it then, you can filter keywords from dir():

__all__ = [ helper for helper in dir() if helper == MY_CONDITION ]
like image 96
Antoine Pelisse Avatar answered Nov 15 '22 16:11

Antoine Pelisse


Yes, by simply not specifying __all__.

like image 27
Gandaro Avatar answered Nov 15 '22 15:11

Gandaro


If you don't define __all__ then all of the functions in your module will be imported by calling from helpers import *

If you've got some functions that you'd like to keep private, then you could prefix their names with an underscore. From my testing, this stops the functions from being imported by import *

For example, in helper.py:

def _HiddenFunc():
    return "Something"

def AnActualFunc():
    return "Hello"

Then:

>>> from helper import *
>>> AnActualFunc()
'Hello'
>>> _HiddenFunc()
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
NameError: name '_HiddenFunc' is not defined
like image 20
obmarg Avatar answered Nov 15 '22 16:11

obmarg