user2329125
user2329125

Reputation:

Is it possible to share a namespace across multiple files

Basically I have the problem of circular dependencies and I can not change to class structure of the code I am working with ( Please don't suggest to change the class structure).

Now I could put all my code into one giant file, but that does not seem practical.

So is it possible that all my classes live in the same namespace, so that this would be possible:

File a.py:

from b import B
class A:
    def foo(self):
        B().bar()

    def bar(self):
        print("Hello, this is A")

File b.py:

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

    def bar(self):
        print("Hello, this is B.")

Without python exploding in on itself.

Upvotes: 4

Views: 1396

Answers (2)

Eric Renouf
Eric Renouf

Reputation: 14520

If you can't change the file structure and/or class hierarchy, you could just move the import lines to a place where they don't end up importing each other. They'd get executed many times, but if you don't mind the performance impact of that you could move the import lines to inside the foo definitions like

class A:
    def foo(self):
        from b import B
        B().bar()

and the analog on the B side.

Probably refactoring is the better way to go, or use the qualified names as @RonaldOussoren shows in his answer.

Upvotes: 2

Ronald Oussoren
Ronald Oussoren

Reputation: 2810

It is not possible to have two modules that share the same namespace. What you can do in your example is to use import a instead of from a import A and then reference the class as a.A (and likewise for class B in the other module).

Upvotes: 1

Related Questions