Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use *args in a dataclass?

I recently started using dataclasses and they will be a nice addition to 3.7. I'm curious if or how it is possible to recreate the same functionality of this class using dataclasses.

class Nav(object):
    def __init__(self, name:str, menu, page, *submenus):
        self.name = name
        self.menu = menu
        self.page = page
        self.submenus = submenus

foo = Nav("name", "menu", "page")

This doesn't work. Raises Exception TypeError: __init__() missing 1 required positional argument: 'submenus'

@dataclass
class Nav(object):
    name:str
    menu: Any
    page: Any
    submenus: tuple

foo = Nav("name", "menu", "page")

I assume this is because the class doesn't have the instructions to do the unpacking of the arguments. Is there some way to instruct the dataclass decorator that submenus needs to be unpacked?

like image 497
Marcel Wilson Avatar asked Jun 08 '18 16:06

Marcel Wilson


People also ask

Can a Dataclass have methods?

dataclasses has a special method called __post_init__ . As the name clearly suggests, this method is called right after the __init__ method is called. Going back to the previous example, we can see how this method can be called to initialize an internal attribute that depends on previously set attributes.

How does Dataclass work in Python?

DataClasses are like normal classes in Python, but they have some basic functions like instantiation, comparing, and printing the classes already implemented. Parameters: init: If true __init__() method will be generated. repr: If true __repr__() method will be generated.

How do you initialize a Dataclass in Python?

Defining a data class. A Python class is a program used to create objects and their properties. We use the keyword class to create a class in Python. For class attributes to be initialized, we use a constructor method called __init__() which is called when an object is created in a Python class.

What is a Dataclass?

A data class refers to a class that contains only fields and crude methods for accessing them (getters and setters). These are simply containers for data used by other classes. These classes don't contain any additional functionality and can't independently operate on the data that they own.


1 Answers

I see in the PEP an example of how to override the __init__.

Sometimes the generated init method does not suffice. For example, suppose you wanted to have an object to store *args and **kwargs:

@dataclass(init=False)
class ArgHolder:
    args: List[Any]
    kwargs: Mapping[Any, Any]

    def __init__(self, *args, **kwargs):
        self.args = args
        self.kwargs = kwargs

a = ArgHolder(1, 2, three=3)
like image 114
Marcel Wilson Avatar answered Nov 04 '22 08:11

Marcel Wilson