If we have multiple classes in a single Python file, is it possible to import modules or libraries independently in those classes?
I have found that unlike Java, Python has no style guide that suggests to separate classes in individual files. Even the Python modules have multiple classes; for example the calendar
module has 10 classes in a single file (calendar module source code).
In my scenario,
I have a Python file called planet.py
. It has multiple classes. One of the classes requires to import pyttsx3
module. Then it needs to get a reference to the pyttsx3.Engine
instance before using it. Currently I am importing the module and creating the instance in class __init__
method like below.
class Animal:
pass
class Speaker:
def __init__(self):
import pyttsx3
self.engine = pyttsx3.init()
def speak(self, text):
self.engine.say(text)
self.engine.runAndWait()
Some other programmers suggest me not to import modules inside functions. They said it will execute the import statement every time the function is called.
I do not know how to do so. Apart from the main question, what is the best practice to follow in scenarios like this?