24

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?

6
  • Python3.7 is not stable now. Maybe this is just a bug?
    – Sraw
    Commented Jun 8, 2018 at 16:31
  • 5
    Unpopular opinion: That's not how varargs should be used. Just use a list.
    – Aran-Fey
    Commented Jun 8, 2018 at 16:33
  • @JaredSmith I added a better example of how it doesn't work. Commented Jun 8, 2018 at 16:39
  • By the way, when typing tuples unless you know the concrete type and length or are making immutability part of the API contract, I'd use Iterable instead. I'd use that instead of List too. Commented Jun 8, 2018 at 16:41
  • 1
    [untested idea]try manually unpacking in post-init[/untested idea]
    – cmc
    Commented May 27, 2019 at 12:37

1 Answer 1

17

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)
4
  • 3
    My thoughts exactly. The decorator gives you a nice __repr__, but yeah I'm a little disappointed. Commented Jun 8, 2018 at 16:40
  • 3
    A year later and I have to take back my comment. Raymond Hettinger gave a talk at PyCon 2018 going over why the dataclass is still pretty great (even if we have to override the init) youtube.com/watch?v=T-TwcmT6Rcw Commented Jun 20, 2019 at 15:58
  • It seems like, if you use this, then you can't use frozen=True. Such a shame!
    – Adamsan
    Commented Dec 1, 2023 at 19:22
  • Really? I'm curious if there is still a way to trigger the dataclass into a 'frozen' state, like in the __post_init__? Commented Sep 4 at 16:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.