Reputation: 9452
class A():
def __init__(self):
install_package('abc')
import abc
def sq(self):
print(abc.sqrt(5))
Background
I am writing helper classes (all stored in a helper.py
) for my clients who use python to run a application(which I send them). These helper classes help the application function. To allow for quicker deployment on client side, I wrote a function called install_package
that implicitly calls pip install
.
All clients receive the same helper.py
file but a different application. The application I send them usually use a subset of classes from helper.py
.
Motive
So the reason I use the above class structure is now pretty obvious, I do not want to load all the libraries in the start of the helper.py
as the libraries will have a corresponding install_package()
with them. So for a client who's application may not use all the classes, there is no need to install all the unnecessary libraries
Issue
Now the issue is that using the above structure to A()
seems like a feasible option but the package that I import in the __init__
function does not get globally imported and hence sq()
cannot use functions in the abc
library. What's the best way to fix this? One way would be to store the library in a variable local to the class
. How would I go about doing it? Suggestions to change the class structure also welcome!
Upvotes: 3
Views: 446
Reputation: 59701
What about something like this:
import importlib
class A():
def __init__(self):
install_package('abc')
self.abc = importlib.import_module('abc')
def sq(self):
print(self.abc.sqrt(5))
Upvotes: 2