Re: PEP Idea: Extended import syntax for aliasing module attributes

Rob Cliffe via Python-list <[email protected]>
Newsgroups gmane.comp.python.general
Message-ID <[email protected]>

On 17/06/2025 00:19, Omar Ahmed via Python-list wrote:
> Hi all,
> I would like to propose a potential addition to Python's `import` syntax that would improve clarity and ergonomics for cases where developers want both full module access *and* a local alias to a specific attribute within that module.
>
> Currently, to get both behaviors, we typically write:
> import module
> optimize = module.optimize
>
> This works fine, but it is slightly verbose and less explicit in intent.
>
> I would like to explore syntax like:
> import module with module.optimize as optimize
> or possibly:
> import module with (
>      module.optimize as optimize,
>      module.validate as check
> )
>
> The goal is to import the full module as usual, while simultaneously assigning a local name to a chosen sub-attribute all in a single declaration.
>
> This strikes a balance between:
> *Readability* (makes intensions clearer)
> *Convenience* (avoids repetitive alias assignments)
> *Maintainability* (discourages `from module import *`)
>
> I am curious to hear whether this type of syntax has been considered before, or if it might be worth formalizing into a PEP. I would be happy to help develop a draft proposal if there is interest.
>
> Thank you for reading.
> -Omar
If the only module attrributes you want are the ones you list 
explicitly, you can already write

from module import (
     optimize,
     validate as check
)

Explicit, convenient, readable and less verbose!
Of course if you do this, you will get a NameError if you subsequently do
     module.someOtherAttribute
or even just
     module
So this may or may not meet your use case.
If it does, it is arguably an advantage that
     your namespace is not cluttered by having "module" in it
     You have explicitly documented which attributes of "module" your 
code uses,
     and will get an error if you try to use a different one without 
listing it.
If not, you can just add
     import module
(slightly clunky in that you now have 2 import statements referring to 
the same module,
but as I understand it will not be significantly slower - the module 
will only be imported once).
Best wishes,
Rob Cliffe
-- 
https://mail.python.org/mailman3//lists/python-list.python.org
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.