0

I have a folder called myPackage which contains

  • a file called myModule.py
  • an empty file called __init__.py

The file myModule.py is as follows:

def foo():
    print("Hello!")

Now each of the following files would run smoothly and do what I expect:

First option:

import myPackage.myModule
myPackage.myModule.foo()

Second option:

from myPackage import myModule
myModule.foo()

Third option:

from myPackage.myModule import foo
foo()

My question is what happens if I run a script containing:

import myPackage

The import alone does make the interpreter complain... but then I would have expected the following to work:

myPackage.myModule1.foo()

which is not the case.

Can I do import myPackage? I guess so, since otherwise I would have gotten an error straight away... What am I supposed to do next?

Chicken
  • 113
  • 7
  • TL;DR: `import myPackage` imports `myPackage`, but not any submodules of it. If `myPackage` contains something like `from . import myModule`, then `myModule` is a name define in `myPackage` and is thus available as `myPackage.myModule` without doing anything else. If `myPackage` does *not* `import myModule`, then you can't access it, unless and until you `import` it explicitly. – deceze May 04 '21 at 12:22
  • @deceze sorry you lost me. how to can myPackage contain something like from . import myModule? myPackage is just a folder. – Chicken May 04 '21 at 12:30
  • `__init__.py`... – deceze May 04 '21 at 12:32

1 Answers1

-1

I usually write this to import customed packages:

from myPackage import *

The file is in the same folder as the file where I import it. I can the just call all the methods without putting everything in every command (so, not myPackage.myModule1.foo() but just foo()).

hellomynameisA
  • 546
  • 1
  • 7
  • 28