0

I know what * and ** do in Python (e.g. What do the * (star) and ** (double star) operators mean in a function call?). But if I want to create my own "dict-like" class. I'm wondering if ** maps to some dunder method that I can add to my class such that my class can respond to ** in a similar way. If not a dunder, is there some other way to create a fully dict-like class that does support a ** prefix operator?

(Bonus points for the same on a tuple-like class for *, but it's the dict version I need a solution to!)

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
dsz
  • 4,542
  • 39
  • 35
  • 3
    For `*` unpacking the class must be iterable, defining a `__iter__` method. For `**` keyword unpacking, it must adhere to a dict interface. One way is to extend `collections.abc.Mapping` – flakes Jan 30 '23 at 01:28
  • As far as I can find, unpacking doesn't correspond to any dunder methods. But you can subclass from dict, or even better, from UserDict in collections, to get the mapping functionality. – Matthew B Jan 30 '23 at 01:31
  • 1
    The question is a slighlty different question, but the answer is definitely in the "dupe" question. Not deleting as this may still be useful to navigate to the answer - very hard searching on `*` and `**`! – dsz Jan 30 '23 at 02:12

1 Answers1

-4

In python, the * and ** means:

  • *args (Non Keyword Arguments)
  • **kwargs (Keyword Arguments)

*args allow us to pass the variable number of non keyword arguments to function.

For example,

def fn(*num):
    sum = 0
    
    for n in num:
        sum = sum + n

    print("Sum:",sum)

fn(1,2)
fn(4,5,6,7)
fn(1,2,3,5,6)

The output will be,

Sum: 3
Sum: 22
Sum: 17

**kwargs allows us to pass the variable length of keyword arguments to the function.

def intro(**data):
    print("\nData type of argument:",type(data))

    for key, value in data.items():
        print("{} is {}".format(key,value))

intro(Firstname="John", Lastname="Doe", Age=15, Phone=1234567890)
intro(Firstname="Albert", Lastname="Jackson", Email="ajackson@somemail.com", Country="UK", Age=45, Phone=88888888)

If we run the above program, the output will be

Data type of argument: <class 'dict'>
Firstname is John
Lastname is Doe
Age is 15
Phone is 1234567890

Data type of argument: <class 'dict'>
Firstname is Albert
Lastname is Jackson
Email is ajackson@somemail.com
Country is UK
Age is 45
Phone is 88888888
  • 4
    You missed the point of the question. Its about how to support unpacking behavior on custom classes. – flakes Jan 30 '23 at 01:26