tags:

views:

97

answers:

5

Hi, I come from Java and I wanna do some Data Transfer Objects like this:

class ErrorDefinition():
    code = ''
    message = ''
    exception = ''

class ResponseDTO():
    sucess = True
    errors = list() # how to say it that is directly of ErrorDefinition() type, to not import it every time that im going to append a Error def.

or Is there a better way to do this?

A: 

I'm pretty sure you cant define a type for a list. You're going to need to import ErrorDefinition everytime ( which looks like the already existing Exception class )

Juan
+5  A: 

Python is dynamically typed, you just don't declare types for variables like you do in Java. The official tutorial is highly suggested reading at this stage: http://docs.python.org/

Vladimir Gritsenko
A: 

DTO is a design pattern for Java. Trying to use Java semantics in Python is not going to work. You need to step out another level and ask. This is the problem I am trying to solve ... , in Java I would use DTO - how would you approach it using Python?

gnibbler
...and the answer is usually something like "oh, I can use a tuple" or "oh wait, I don't actually have that problem in Python". ;-)
Jason Orendorff
Yeah, there must be a reason why complicated design patterns like DTO don't show up much for Python, huh?
gnibbler
+1  A: 

errors = list() # how to say it that is directly of ErrorDefinition() type, to not import it every time that im going to append a Error def.

I am not sure what you are trying to say in this comment, but if I understand right, the best way to get something close is to define a method to add an error.

class ResponseDTO(object): # New style classes are just better, use them.

    def __init__(self):
        self.success = True # That's the idiomatic way to define an instance member.
        self.errors = [] # Empty list literal, equivalent to list() and more idiomatic.

    def append_error(self, code, message, exception):
        self.success = False
        self.errors.append(ErrorDefinition(code, message, exception))
ddaa
A: 

Please explain what you mean by "import it every time".

You need to reconsider using class-level attributes before you have explored exactly what they do, especially when you use mutable types like lists. Consider this:

>>> class Borg(object):
...     alist = list()
...
>>> a = Borg()
>>> b = Borg()
>>> a.alist.append('qwerty')
>>> a.alist
['qwerty']
>>> b.alist
['qwerty']
>>>

Not what you wanted? Use the usual Python idiom of setting up what you need in the class's __init__ method:

>>> class Normal(object):
...     def __init__(self):
...         self.alist = list()
...
>>> x = Normal()
>>> y = Normal()
>>> x.alist.append('frobozz')
>>> x.alist
['frobozz']
>>> y.alist
[]
>>>
John Machin