[Python-ideas] Make `import a.b.c as m` is equivalent to `m = sys.modules['a.b.c']`
Victor Varvariuc
victor.varvariuc at gmail.com
Sun Apr 9 07:03:59 EDT 2017
Thanks for the reply. CC'ing the mailing list.
> On 9 Apr 2017, at 10:05, Nick Coghlan <ncoghlan at gmail.com> wrote:
>
> On 9 April 2017 at 16:13, Victor Varvariuc <victor.varvariuc at gmail.com> wrote:
>> I think there are can be several ways to achieve the result.
>>
>> The question is if what I've presented is a valid concern. I think this would make the language more consistent and help reducing number of errors related to import without breaking old code.
>>
>> May I create an issue in the bug tracker?
>
> Aye, go ahead - I would previously have advised against it, but given
> at least one relatively low impact path to resolution, it's worth
> filing it as an enhancement request.
>
> Cheers,
> Nick.
>
> --
> Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
> Begin forwarded message:
>
> From: Nick Coghlan <ncoghlan at gmail.com>
> Subject: Re: [Python-ideas] Make `import a.b.c as m` is equivalent to `m = sys.modules['a.b.c']`
> Date: 9 April 2017 at 08:33:43 GMT+3
> To: Victor Varvariuc <victor.varvariuc at gmail.com>
>
> On 8 April 2017 at 22:57, Victor Varvariuc <victor.varvariuc at gmail.com> wrote:
>> Thanks, Nick, for the thorough explanation.
>>
>> changing those semantics isn't as
>> simple as just having the compiler reinterpret "import x.y.z as m" as
>> "from x.y import z as m"
>>
>>
>> I don't think this is a solution.
>>
>> The solution, IMO, is to treat `import x.y.z as m` as `m =
>> __import__('x.y.z')` (or similar, IIRC).
>
> That's not quite how the `__import__` hook works: when the fromlist is
> empty, it returns the *base* module, not the most resolved one.
>
>>>> __import__("unittest.mock")
> <module 'unittest' from '/usr/lib64/python3.5/unittest/__init__.py'>
>
> However, the idea does indicate a potential resolution, which would be
> to add a new IMPORT_ATTR opcode with roughly the following semantics:
>
> try:
> _op_result = getattr(obj, ATTR)
> except AttributeError:
> _package_name = obj.__package__
> if not _package_name:
> raise
> _op_result = sys.modules[_package_name + "." + ATTR]
>
> And then have the import statement unconditionally emit IMPORT_ATTR
> instead of LOAD_ATTR for the "import x.* as y" case.
>
> Cheers,
> Nick.
>
> --
> Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20170409/5baa2f9b/attachment.html>
More information about the Python-ideas
mailing list