Srini
Srini

Reputation: 1649

Relative Imports in Python correct syntax and requirements

I know this horse has been flogged countless times but none of the answers answer my question

My folder structure is as follows

/pdocs
    __init__.py (empty)
    file1.py
    tester.py
    Test/
        __init__.py (empty)
        file2.py

file1.py is as follows

class file1:
    def sayhi():
        print "hi from parent"

file2.py is as follows

from ... import file1
class file2:
    def sayhitoo():
        print "Hi from child"

tester.py is as follows

from Test.file2 import file2
sayhi()
sayhitoo()

Tryin to run tester.py I get

"from ... import file1"
"ValueError: Attempted relative import beyond toplevel package"

What does this mean. What should I change?

Upvotes: 0

Views: 80

Answers (1)

Alex Martelli
Alex Martelli

Reputation: 882401

You're trying to import from "two levels up" -- that's what the three dots in ... mean. You're importing from just one level up, so, use .. instead.

There are other problems too -- e.g, after importing file2, you could call file2.sayhitoo(), but what you're trying to call instead is a bareword (unqualified) sayhitoo, which won't work (I predict a NameError). Same, squared, in the attempt to call bareword sayhi. But, these are yet further errors besides the one you're asking about:-).

Upvotes: 2

Related Questions