How to make unique objects accessible in other modules of Python?


This is basically the idea of a singleton object. So if you have instantiated an obect and want to access it across different module, you can use 2 approaches, first being you assign that variable to the module you imported under a variable name. For example, you have a object myobj instantiated and want to use it with module B, then you can do the following:

>>> import B
>>> B.myobj = myobj

And inside module B, use it like any other global property. Another way is to accept this object as a parameter wherever required. For example, if you have a function myfunc in module B that requires this object, you can do the following,

>>> import B
>>> B.myfunc(myobj)

Updated on: 01-Oct-2019

218 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements