1

I'm new to Python from a Java background and I'm trying to construct DTOs to wrap my data as I would with Java Collections framework by extending a collection.

public class MyDto<T> extends ArrayList<T> implements MyDtoInterface<T> { ... }

I've read python-quick-and-dirty-datatypes-dto and it seems to provide a basis for what I need. However what I cannot figure from the accepted answers is how to make my dto a type rather than a wrapper. The accepted answer is a python script rather than a class. I want to avoid having to do this:

class NamedDto(namedtuple):
    data = namedtuple("first", "second", "etc")

dto = NamedDto()
dto.data.first = 1
dto.data.second = 2
dto.data.etc = None
print(dto)

and instead do this:

dto = NamedDto()
dto.first = 1
dto.second = 2
dto.etc = None

and/or

dto = NamedDto(1,2,3)
print(dto.first)
print(dto.second)
print(dto.etc)

I've also read, which don't seem to answer this specific question.

Martin of Hessle
  • 394
  • 3
  • 12
  • "However what I cannot figure from the accepted answers is how to make my dto a type rather than a wrapper. " i'm not sure what you mean here. It *is* a type. – juanpa.arrivillaga Dec 04 '18 at 10:12
  • Anyway, `namedtuple` objects are *tuples*, they do not support item assignment or attribute assignment like that. Also, you are not using the `namedtuple` type factory correctly. `class MyType(namedtuple)` doesn't work, `namedtuple` is not a class, it is a class factory, so you would need to call `namedtuple`, somnething like `namedtuple('MyBaseClass', 'arg1 arg2')` or else it will probably would throw a runtime error It *sounds* like you just want a class. Why are you even messing around with a `namedtuple` to begin with? – juanpa.arrivillaga Dec 04 '18 at 10:14
  • @juanpa.arrivillaga yes namedtuple is a type but I want to create a type that extends namedtuple, not an instance of it as per the accepted answer. – Martin of Hessle Dec 04 '18 at 10:19
  • No, `namedtuple` *returns* a type (i.e a class, a subclass of `tuple` to be precise). `namedtuple` is just a function, it is a class factory. – juanpa.arrivillaga Dec 04 '18 at 10:20
  • But why do you want to *extend* the built-in types? This is not a common python idiom at all. Generally, favor composition. Again, it sounds like you *just want a plain class*, what, exactly, does inheriting from some `tuple` subclass gain you? – juanpa.arrivillaga Dec 04 '18 at 10:21

0 Answers0