Polymorphic imports

Chris Angelico rosuav at gmail.com
Tue Sep 21 16:23:43 EDT 2021


On Wed, Sep 22, 2021 at 6:05 AM <2QdxY4RzWzUUiLuE at potatochowder.com> wrote:
>
> On 2021-09-22 at 05:10:02 +1000,
> Chris Angelico <rosuav at gmail.com> wrote:
>
> > You can dynamically import modules using importlib.import_module(),
> > but an easier way might just be a conditional import:
> >
> > # client/__init__.py
> > if some_condition:
> >     import module_a_default as module_a
> > else:
> >     import module_a_prime as module_a
> >
> > Now everything that refers to client.module_a.whatever will get the
> > appropriate one, either the original or the alternate.
>
> +1
>
> > Alternatively, since you are talking about paths, it might be easiest
> > to give everything the same name, and then use sys.path to control
> > your import directories. Not sure which would work out best.
>
> -1
>
> Please don't do that.  Mutable shared and/or global state (i.e.,
> sys.paths) is the root of all evil.  And homegrown crypto and date
> libraries.  And those funny red hats.

All depends on whether this is a script/application or a library. If
it's a library, then I agree, don't mutate sys.path, don't change the
working directory, etc, etc, etc. But applications are free to do
those sorts of things. I don't know what the OP's purpose here is, and
it's entirely possible that sys.path switching is the cleanest way to
do it.

ChrisA


More information about the Python-list mailing list