Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid duplicate name when importing a sub-module with only one public member from a package

Tags:

python

Basic Setup

Suppose I want to create a class named Foo. I may create a file like so:

foo.py:

class Foo:
    def __init__(self):
        self.data = "world"
    def print(self):
        print("Hello, " + self.data)

To utilize this class in my main script:

main.py

import foo

test = foo.Foo()
test.print()

Having to type foo.Foo() every time I instantiate the class already feels ridiculous enough, but it gets worse when I want to organize my code by separating my classes into a package:

classes/__init__.py

# Empty

classes/foo.py

# Copy of foo.py, above

main.py

import classes.foo

test = classes.foo.Foo()
test.print()

Simple Answer

I know I can clean this up somewhat by using from X import Y like so:

from classes.foo import Foo

test = Foo()

Preferred Answer

Because the file foo.py contains only one member whose name matches the file, I would prefer if I could do something like the following:

from classes import Foo
# Or:
import classes.Foo as Foo

test = Foo()

Is there a way to do this? Maybe with some code in my __init__.py?

like image 207
stevendesu Avatar asked Oct 25 '25 10:10

stevendesu


1 Answers

In classes/__init__.py, put:

from .foo import Foo

Now you can write from classes import Foo.

like image 86
Alex Hall Avatar answered Oct 27 '25 00:10

Alex Hall



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!