0

Suppose I have a module named 'module1', which has many classes. I want to use all of their classes in my main controller main.py . I can import whole module with import module1, however, I assume that the class names in 'module1' are unique and I do not want to reference module1 every time I call its function such as module1.class1().

How can I import the whole contents of a module without explicitly having to state class/function names and still being able to refer to them without stating the module name.

Such as:

    # module1.py.
    class Class1():
        pass
    
    class Class2():
        pass
    # __main__.py
    import module1
    
    # The following will not work.
    object1 = Class1()
    object2 = Class2()
wakey
  • 2,283
  • 4
  • 31
  • 58
brikas
  • 194
  • 1
  • 13

1 Answers1

0

You can use the * import pattern

from module1 import *

This lets you use everything inside that module without referencing it.

from module1 import *

instance = Class1()

However, this is generally discouraged. For reasons why, some additional reading:

wakey
  • 2,283
  • 4
  • 31
  • 58
  • That's usually recommended against as it's easy to import *really unexpected* things and create gnarly dependencies. For instance it'll also "import" everything else that `module1` defines *or imports*. `from module1 import Class1, Class2` works fine though. – Masklinn Nov 20 '20 at 15:06
  • @Masklinn I 100% agree, I added a link to some additional reading on why not to do this. Feel free to suggest alternative/additional resources – wakey Nov 20 '20 at 15:07