Reputation: 20698
I'm creating objects by composition. So
class OMX:
def __init__(self):
pass
class PYG:
def __init__(self):
pass
class AudioPlayer:
def __init__(self):
audioController = None
if someCondition:
audioController = OMX()
else:
audioController = PYG()
OMX requires import subprocess
, but PYG does not. So I don't want to unnecessarily put a global import subprocess
. So I was considering putting the import in the __init__
of OMX like this:
class OMX:
def __init__(self):
import subprocess
Is this good practice in Python?
Upvotes: 0
Views: 49
Reputation: 8594
PEP 8 has this to say:
Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.
More practically, you should consider that importing something in a constructor does not automatically make it available to methods.
Upvotes: 2