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

PythonServer Side ProgrammingProgramming

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)
raja
Published on 21-Dec-2017 10:51:10
Advertisements