Nav
Nav

Reputation: 20698

What is a good practice to follow when importing libraries/packages in python when it's not global?

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

Answers (1)

Brian McCutchon
Brian McCutchon

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

Related Questions