2

I have a directory that contains several .py files/modules. In that directory, I put __init__.py within with an intent to make it a package. What I would like to have is, when I import the directory, I would access all the methods from individual modules without specifying each module name inside __init__.py. This means, when I would add a new module, __init__.py would pick it up and I am free off manual update of that module name inside of __init__.py. Here is an example to show what I want:

/my_package/
   module1.py
   module2.py
   ..........
   ..........
   moduleN.py

Now,

within module1.py, I have def add(n,m):

within module2.py, I have def sub(n,m): etc. etc.

Now, suppose in Jupyter lab, I import like this,

import my_package as mpgk

then I would like to access mpkg.add, mpkg.sub

What do I need to do inside __init__.py to make sure the methods from individual modules from that directory are loaded?

Jonathon McMurray
  • 2,881
  • 1
  • 10
  • 22
  • Welcome to StackOverflow. You should use `code` sections to format your question. Please read [this](https://stackoverflow.com/help/how-to-ask). – Tim Nov 29 '19 at 14:46
  • Why not just use `from my_package.module1 import *`? – Tim Nov 29 '19 at 14:46
  • 1
    `from module1 import *` etc to refer to the functions/classes from the module1 directly. | As for picking up every module, even a new one... that's more complicated. Why do you even need this? This seems like a bad design. Firstly, name collisions. Secondly, it looks like Java approach "everything in a different file", and this is not Java, it's Python, we do things differently here. (Basically, why even have modules if you're gonna import everything at once without exceptions???) – h4z3 Nov 29 '19 at 14:48
  • 2
    Possible duplicate of [How to import all submodules?](https://stackoverflow.com/questions/3365740/how-to-import-all-submodules) – Davis Herring Nov 29 '19 at 15:47

0 Answers0