1

I have a module with the structure:

- mymodule
  - mymodule
      __init__.py
      core.py
  setup.py

__init__.py contents:

from .core import MyClass

So now when I import my module I have to do:

import mymodule

mymodule.MyClass()

but what I want is:

import mymodule

MyModule()

but I don't want to have to:

from mymodule import MyModule

Can this be done and if so how?

xendi
  • 2,332
  • 5
  • 40
  • 64
  • 1
    Why on earth wouldn't you want to use the `from` keyword? If it's not just laziness, this definitely needs more context. – SeedyROM May 02 '20 at 08:17
  • 2
    There are some hacks, check out this post: https://stackoverflow.com/questions/1060796/callable-modules. But why don't you want to explicitly import the stuff you need? – user2390182 May 02 '20 at 08:18
  • No, it cannot. That is simply not how python imports work vis a vis namespaces – juanpa.arrivillaga May 02 '20 at 08:19
  • what if in the __init__() I instantiate the MyModule class and return it? – xendi May 02 '20 at 08:21
  • @xendi What are you trying to accomplish here? This isn't Ruby or C/C++ you can't just import all functions, classes, etc sanely into a module without the from keyword. – SeedyROM May 02 '20 at 08:22
  • Just thinking of how to make it easier for the user – xendi May 02 '20 at 08:23
  • 2
    Who is the user? If they're a python programmer they should understand how the `from` keyword works. You're getting too far ahead of yourself here. – SeedyROM May 02 '20 at 08:24
  • alright then, thx – xendi May 02 '20 at 08:27

1 Answers1

0

The closest you can get is star import:

from mymodule import *
RafalS
  • 5,834
  • 1
  • 20
  • 25
  • This is the correct answer unless you plan on using `exec` to dynamically inject modules into the module, which is f**king nasty but I should note can be done. – SeedyROM May 02 '20 at 08:25