1

I'm new to Python and I'm trying to figure out how to best organize my code. I'm planning on adding a few classes in their own files and I'd like to reference the classes without having to specify the file name. For example let's say I have a structure like this:

my_project/
└── module1/
    ├── A.py
    └── B.py

A.py

class A:
    def foo(self):
        raise NotImplementedError

B.py

class B:
    def foo(self):
        raise NotImplementedError

Now let's say I want to reference class A in B.py. How can I make it so that B.py looks like this:

import A
class B:
    def foo(self):
        return A()

and not like this:

from a import A
class B:
    def foo(self):
        return A()

Essentially, I'd like to group classes into one namespace without having to put all of my classes into one file.

1 Answer 1

1

First of all, you would need to correct the syntax of the class, your classes should be

class A:
    def foo(self):
        raise NotImplementedError

and

from a import A

class B:
    def foo(self):
        return A()

Now the reason you need to do from a import A and not import A is because A is a class which lives in a python file .py, and you need to tell the interpreter where the class A is defined, otherwise the interpreter doesn't know where to find A

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for pointing out the syntax bugs. Follow up to your answer, for the pandas library, I'm able to import DataFrame by adding from pandas import DataFrame, but based on the source code, it looks like I'd have to put from pandas.core.frame import DataFrame. Same thing goes for the Series class. How is pandas set up differently?
I haven't used pandas library, so unfortunately I cannot answer this for you. It is better you should ask a new question for it. Also please accept my answer if it helped you
@Hydrosis pandas imports specific submodules into its top level module as well. This is done by putting imports into the pandas/__init__.py file: github.com/pandas-dev/pandas/blob/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.