Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class that acts as mapping for **unpacking

Without subclassing dict, what would a class need to be considered a mapping so that it can be passed to a method with **.

from abc import ABCMeta  class uobj:     __metaclass__ = ABCMeta  uobj.register(dict)  def f(**k): return k  o = uobj() f(**o)  # outputs: f() argument after ** must be a mapping, not uobj 

At least to the point where it throws errors of missing functionality of mapping, so I can begin implementing.

I reviewed emulating container types but simply defining magic methods has no effect, and using ABCMeta to override and register it as a dict validates assertions as subclass, but fails isinstance(o, dict). Ideally, I dont even want to use ABCMeta.

like image 688
dskinner Avatar asked Dec 22 '11 08:12

dskinner


People also ask

What is the unpacking operator in Python?

In short, the unpacking operators are operators that unpack the values from iterable objects in Python. 00:30 The single asterisk operator ( * ) can be used on any iterable that Python provides, while the double asterisk operator ( ** ) can only be used on dictionaries.

What is packing and unpacking?

A general look at packing and unpacking. Iterable unpacking refers to the action of assigning an iterable of values to a tuple or list of identifiers within a single assignment; Iterable packing refers to the action of capturing several values into one identifier in a single assignment.

How do you unpack a string in Python?

Method : Using format() + * operator + values() The * operator is used to unpack and assign. The values are extracted using values().


2 Answers

The __getitem__() and keys() methods will suffice:

>>> class D:         def keys(self):             return ['a', 'b']         def __getitem__(self, key):             return key.upper()   >>> def f(**kwds):         print kwds   >>> f(**D()) {'a': 'A', 'b': 'B'} 
like image 172
Raymond Hettinger Avatar answered Sep 22 '22 21:09

Raymond Hettinger


If you're trying to create a Mapping — not just satisfy the requirements for passing to a function — then you really should inherit from collections.abc.Mapping. As described in the documentation, you need to implement just:

__getitem__ __len__ __iter__ 

The Mixin will implement everything else for you: __contains__, keys, items, values, get, __eq__, and __ne__.

like image 34
Neil G Avatar answered Sep 24 '22 21:09

Neil G