I’m trying to find out how exactly importing works in Python.
Let’s say I have a foo.py module that contains the following class:
class Foo:
def __init__(self, *args, **kwargs):
...
foo = Foo()
Now, I want to import it in other modules.
Is it going to use the same instance every time that I import it or will make different instances whenever I import it and is it even a good way to instantiate a class or it’d be better to import the Foo class and create an instance in modules that imported it(As it’s obvious, this class doesn’t need any args and kwargs).
>Solution :
Import it in the usual way:
from foo import Foo
If this is the first time, the foo.py code will execute and the “class” / “def” statements will generate bytecode for the interpreter.
And we make a note of it in sys.modules.
Subsequent imports will benefit from a cache hit, so we won’t repeat all that evaluation work.
Bottom line: you get exactly one instance of the code in that class.