Importing modules with arguments

Chris Angelico rosuav at gmail.com
Fri Jul 30 15:25:16 EDT 2021


On Sat, Jul 31, 2021 at 5:11 AM Charles Smith <charles at sollum.tech> wrote:
>
> First off, thanks for the answer. I don't see the cached module as a problem here. If you provide arguments to a module, the goal is "most likely" to alter/parameterize the behavior of the first import. Now, I agree that behavior becomes unpredictable because passing different parameters on subsequent imports won't change the behavior of the imported module .
>

The trouble is that if any other module has already imported the one
you're trying to parameterize, then your code won't know that the
parameters haven't been applied. It's action at a distance.

> One thing that could be done is to memoize those imports based on the parameters (this is a huge change to how imports works so its a bit yikes).

That's functionally equivalent to importing a class and then
instantiating, but with an automated cache. Could be interesting, but
belongs inside the module, not as a language mechanic, IMO.

> Another solution would be to simply not cache parameterized imports. You sacrifice performance for added flexibility which I think is fair.

And that's functionally equivalent to importing a class and then
instantiating, *without* the automated cache. :)

> I do however agree about partial imports. It would be rather complex to properly pass the context but its certainly doable.
>

Yeah.

So here's a possibility. Craft a module-level __getattr__ function
that does the caching behaviour you want. Then you can "from
modulename import Thing", where the precise name you want is the
selection of parameter. The __getattr__ function can also set it as an
intrinsic attribute (thus offering high performance caching - it'll
bypass __getattr_ the second time). Other than that, though, there's
not really a lot of parameterization that would make sense as part of
the import (if you need to say something like "import random;
random.seed(12345)", that's not really going to fit into the import
statement).

ChrisA


More information about the Python-list mailing list