Yahya Uddin
Yahya Uddin

Reputation: 28841

Splitting my code into multiple files in Python 3

I wish to split my code into multiple files in Python 3.

I have the following files:

/hello
    __init__.py
    first.py
    second.py

Where the contents of the above files are:

first.py

from hello.second import say_hello

say_hello()

second.py

def say_hello():
    print("Hello World!")

But when I run:

python3 first.py

while in the hello directory I get the following error:

Traceback (most recent call last):
  File "first.py", line 1, in <module>
    from hello.second import say_hello
ImportError: No module named 'hello'

Upvotes: 0

Views: 5867

Answers (3)

Ethan Furman
Ethan Furman

Reputation: 69021

Packages are not meant to be imported from the current directory.

It is possible to make it work using if/else tests or try/except handlers, but it's more work than it is worth.

Just cd .. so you aren't in the package's directory and it will work fine.

Upvotes: 0

Bharel
Bharel

Reputation: 26901

You shouldn't run python3 in the hello directory.

You should run it outside the hello directory and run

python3
>>> import hello.first

By the way, __init__.py is no longer needed in Python 3. See PEP 420.

Upvotes: 0

DaveBensonPhillips
DaveBensonPhillips

Reputation: 3232

Swap out

from hello.second import say_hello

for

from second import say_hello

Your default Python path will include your current directory, so importing straight from second will work. You don't even need the __init__.py file for this. You do, however, need the __init__.py file if you wish to import from outside of the package:

$ python3
>>> from hello.second import say_hello
>>> # Works ok!

Upvotes: 1

Related Questions