[Python-ideas] Unpacking a dict

Joao S. O. Bueno jsbueno at python.org.br
Sun May 29 10:28:02 EDT 2016


On 29 May 2016 at 09:35, Eric V. Smith <eric at trueblade.com> wrote:
> On 5/28/2016 1:34 PM, Joao S. O. Bueno wrote:
>>
>> On 27 May 2016 at 12:37, Zachary Ware <zachary.ware+pyideas at gmail.com>
>> wrote:
>>>
>>> On Fri, May 27, 2016 at 10:32 AM, Michael Selik <michael.selik at gmail.com>
>>> wrote:
>>>>
>>>>
>>>>
>>>> On Fri, May 27, 2016 at 11:28 AM Zachary Ware
>>>> <zachary.ware+pyideas at gmail.com> wrote:
>>>>>
>>>>>
>>>>> Here's a crazy thought that might be best dismissed out of hand: what
>>>>> about extending 'from name import other_names' to accept any object
>>>>> for <name>?  First try to get values via __getitem__() (possibly only
>>>>> for dict/dict subclasses?), next try getattr(), finally try to import
>>>>> the module and pull values from it as per usual.
>>>>>
>>>>> Pros:
>>>>> - solves dict unpacking
>>>>
>>>>
>>>>
>>>> Would it solve nested dict unpacking?
>>>
>>>
>>> How do you mean?  Replacing `some_name =
>>> some_dict['some_key']['some_name']` with `from some_dict['some_key']
>>> import some_name`?
>>>
>>> Sure, why not? :)
>>
>>
>> That is the best idea I've seem on this thread.
>>
>> And them, why having to specify the keys, just to violate DRY?
>>
>> Maybe just allwoing Mappings to be usedwith  `from ...  import ...`
>> syntax
>> will work nicely, unambiguously, with no new weird syntaxes introduced  -
>> and the syntax even allows one to rename the dict keys to other
>> variables, with the
>> `from mymapping  import a as c,  b  as d "   variant.
>>
>> That would be certainly nice.
>
>
> Wouldn't this approach require that the keys be constants? That is, you
> couldn't implement a replacement for:
>
> val = d[key+'bar']
>
> I'm not sure that's a reasonable restriction.


As I posted up on the other thread, I've implemented a poof of concept
for this in a somewhat toyish package I've started earlier.

So right now, one can do
$ pip install extradict
$ python
>>> from extradict import MapGetter
>>> with MapGetter({"a": 1, "b": 2}) as mydict:
...     from mydict import a, b
...
>>> print(a, b)


The code is at http://github.com/jsbueno/extradict  -

(btw, since that e-mail, I've studied the import hook mechanisms and
decided to keep my first
design of temporarily replacing __import__. )

If more people decide to use it, it would be easy to include some more
mapping parameters to
the call to MapGetter to overcome static restrictions of the "import" syntax

with MapGetter(mapping, keysuffix="bar"):
     ...

or rather:

with MapGetter(mapping, keytransform=lambda key: key + 'bar'):
     ...

   js
 -><-


More information about the Python-ideas mailing list