Home > other >  How to do conditional import in Python?
How to do conditional import in Python?

Time:07-26

For example, in my test.py:

from .segmenter import Segmenter

However, this Segmenter may have been imported by another file when used in another way. How to test if Segmenter already exists in the scope, then don't import it?

CodePudding user response:

You could potentially use dir(), which returns a list of all names in the local scope. Something like the expression "Segmenter" in dir() should suffice.

if "Segmenter" not in dir():
  from .segmenter import Segmenter

However, as mentioned in the comments, it's unwise to have imports do anything other than just be imported.

CodePudding user response:

I would use a try/except block like so:

try:
    Segmenter
except NameError:
    from .segmenter import Segmenter
  • Related