Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How Python imports an instance of a class

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).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading