0

So, my problem is that I have a circular import but I also need both of the imports that cause it. In the main file, I have a class that is needed for the second file.

mainfile.py:

class Example:
    def __init__(self, age):
        self.age = age

import secondfile

print(secondfile.main())

secondfile.py:

import mainfile

ex = Example(22)

def main():
    return f"You are {ex.age} years old."

Is there a way to solve this without defining the class again?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • 2
    Does this answer your question? [Python circular importing?](https://stackoverflow.com/questions/22187279/python-circular-importing) – tomgalpin Jul 11 '22 at 12:33
  • in file2, inside main function import example and do things there with example. change the namespace of that import from full import in .py to function only – sahasrara62 Jul 11 '22 at 12:34
  • 1
    Why do you need two files in the first place? – Guy Jul 11 '22 at 12:35
  • 1
    Put `Example` in a third file. – Peter Wood Jul 11 '22 at 12:37
  • I'm with Peter, it's generally better practice to define an object in a separate file. To be honest, I don't see why you need the main function to be declared in the second file, it seems like something which should be in the first as it is a method which pertains specifically to that object. If you're planning on having multiple objects read from that method, I'd consider making a parent class and implementing inheritance. If there's a problem statement you could share, that'd help in deriving a meaningful answer:) – Marco Kurepa Jul 11 '22 at 12:41
  • 2
    Why are you calling `secondfile.main` in the module where you've defined the class in the first place? – ndc85430 Jul 11 '22 at 12:47
  • 1
    This looks more like a contrived example to demonstrate the problem of circular imports than a design you would actually use in practice. If you have a "main" module and a library module, the library module should not depend on the main module in any way. – chepner Jul 11 '22 at 13:16

0 Answers0