2

A project has the following structure:

modulename
├── __init__.py
│
├── one
│   ├── function_1.py
│   ├── function2.py
│   └─── __init__.py
│
└── two
    ├── another_function.py
    ├── yet_another_function.py
    └─── __init__.py

Each .py (except the __init__.py's which are empty) has content along the lines of:

def foo(x):
    return x

def bar(x):
    return x + 2

To use the module you import it it in the following way: import modulename.one.function1.foo. What I want to do is find all .py file names in the second to last place, for example function1 or another_function.

The suggested solutions so far has unsuccessfully been:

  • dir(modulename.one) which results in ['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__'].

  • help(modulename.one) which actually includes the function files' names under the title PACKAGE CONTENTS. How do I get a list of the PACKAGE CONTENTS?

EDIT: I could (as someone suggested) use __all__ in the __init__.py's, but I would prefer a simple built-in function or module.

loading...
  • 162
  • 2
  • 7

1 Answers1

0

I think what you are looking for is the __all__ definition in your packages __init__files.

You can take a look at: http://mikegrouchy.com/blog/2012/05/be-pythonic-__init__py.html

which explains the __all__ behavior in packages.

Martin
  • 5,954
  • 5
  • 30
  • 46
  • That seems like it would work, but as far as I understand you would have to write the `__all__` yourself? Or did I misunderstand? I would prefer if there was a way to find out programmatically. – loading... Aug 07 '17 at 18:19
  • Yes, you would have to write the `__all__` yourself. However, since `__init__.py` is a python module, it might be possible to populate it with code, using glob.glob and importlib.import_module. – Martin Aug 07 '17 at 18:23
  • That would be a possible solution (and if no better answer is posted I will do that). I will still wait for an eventual simpler solution. – loading... Aug 07 '17 at 18:27
  • You can write code to determine that contents of `__all__` at any time in your module (or a package's `__init__.py`). See [this answer](https://stackoverflow.com/a/5135444/355230) of mine for an example. – martineau Aug 07 '17 at 18:41