Hydrosis
Hydrosis

Reputation: 41

Create Python Namespace Without File Name

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.

Upvotes: 1

Views: 370

Answers (1)

Devesh Kumar Singh
Devesh Kumar Singh

Reputation: 20500

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

Upvotes: 1

Related Questions