I want to construct an object from the same class in one of its methods. However, the method is in a different file. How can I do the following?
file1.py
class MyClass():
def __init__(self, i):
print(i)
from file2 import my_fun
file2.py
def my_fun(self):
if i == 1:
new_obj = MyClass(i + 1)
I get the following error:
NameError: name 'MyClass' is not defined
file2has to importfile1.MyClasssomewhere. Importing insidemy_funis of course possible, but not desirable. Doingfrom file1 import MyClassat the beginning of the file will cause a circular dependency problem:MyClassmay not have been executed yet at that point, and so may not exist.Option 1:
In this case,
file1will refer to the correct module object, even if its__dict__is not completely filled in at that point. By the timemy_funcan be called,file1will have been loaded completely.Option 2:
In this version, you place all the import statements after definitions of things imported to another file have had a chance to run. This is not very elegant at all.
Option 3
This is the ugliest option of all. You remove the circular dependency by removing
file2's dependency onfile1. The dependency is exclusive tomy_fun, and does not manifest itself until runtime, when it is totally resolvable. This is not that terrible because after the first execution, the import is basically just assigningTL;DR
You have a couple of ways of bypassing circular dependencies by carefully working around the execution paths of module loading. However, all options shown here are code smell, and you should avoid them. They indicate an inappropriate level of coupling between the modules that should be resolved in other ways.