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?
Import statements should usually be at the top of a python file (convention). According to convention, you should group classes with similar intentions and requirements together in one file. When you import a library, all classes in the file can use them. If a certain class does not need similar imports, or needs a lot of libraries imported which other classes do not need, it should, technically, be in a different file, and the file can be imported and instantiated.
Import statements in functions won't do any harm (apart from a very minimal delay time if run repeatedly), although, as @Evert said, can be a pain to the user experience if they fail.