[Tutor] Querying a packages modules?
Eric Pavey
warpcat at gmail.com
Fri Nov 20 20:14:19 CET 2009
On Fri, Nov 20, 2009 at 10:58 AM, Eric Pavey <warpcat at gmail.com> wrote:
> On Fri, Nov 20, 2009 at 10:40 AM, Dave Angel <davea at ieee.org> wrote:
>
>> Eric Pavey wrote:
>>
>>> On Fri, Nov 20, 2009 at 4:09 AM, Kent Johnson <kent37 at tds.net> wrote:
>>>
>>>
>>>
>>>> On Thu, Nov 19, 2009 at 9:31 PM, Eric Pavey <warpcat at gmail.com> wrote:
>>>>
>>>>
>>>>> Say I have this package layout
>>>>>
>>>>> \myPackage
>>>>>
>>>>> __init__.py
>>>>> moduleA.py
>>>>> moduleB.py
>>>>>
>>>>> Is there a way (and I'm sure there is...) to query, for a given package
>>>>> level, which modules live under it?
>>>>> I thought I could do it like so:
>>>>>
>>>>> import myPackage
>>>>> goodQualityInfo = dir(myPackage)
>>>>>
>>>>>
>>>> One way to do this is to include an __all__ attribute in __init__.p]:
>>>> __all__ = ['moduleA', 'moduleB']
>>>>
>>>> Then instead of dir(myPackage) use myPackage.__all__.
>>>>
>>>> The name is standard though it is usually used for a slightly different
>>>> purpose:
>>>> http://docs.python.org/tutorial/modules.html#importing-from-a-package
>>>>
>>>> Kent
>>>>
>>>
>>> Thanks. I was considering that too, but I want to be able to have people
>>> drop modules in that dir and "be done with it": Not also have them also
>>> need to update __all__ in __init__.py
>>> Appreciate the suggestion though.
>>> My current hacky plan is just query the location on disk of the imported
>>> package, then do a dir search for .py files in that dir, and process
>>> those.
>>> Seems clunky though.
>>>
>>> Doesn't seem clunky to me. And if you do it in __init__.py, you can use
>> the __file__ attribute to get your base directory. Just put the results in
>> __all__ and you combine both ideas.
>>
>> DaveA
>>
>
> Starting to like that more ;)
> thanks
Results. Thanks all.
#---------------------------
# __init__.py
import os
import glob
__all__ = []
packageDir = os.path.split(__file__)[0]
modules = glob.glob( os.path.join(packageDir, "*.py") )
for m in modules:
justModule = os.path.splitext(os.path.split(m)[-1])[0]
# Don't add itself to the list:
if justModule != '__init__':
__all__.append(justModule)
#---------------------------
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20091120/82ac621c/attachment-0001.htm>
More information about the Tutor
mailing list