1

I've got a complex object graph which I need to initialise.

If I doing this in VB.Net, I'd do...

Dim Blah = New A With {
    .B = New C With {.D = New E},
    .F = New G }

In Python, I'm currently doing...

Blah = A()
Blah.B = C()
Blah.B.D = E()
Blah.F = G()
...

Is there a less verbose way of doing this?

Basic
  • 26,321
  • 24
  • 115
  • 201
  • 3
    @FernandoFreitasAlves it's not related – wRAR Mar 18 '13 at 11:41
  • @FernandoFreitasAlves: The Python `with` statement has nothing to do with this. – Martijn Pieters Mar 18 '13 at 11:44
  • 2
    Generally speaking, I'd design my classes to make it easier to build the hierarchy, or use nested dictionaries and/or lists instead for such structures. Or you can build the hierarchy with a helper method from python primitives (`buildStructure(A, (('B', C), ('B.D', E), ('F', G)))`). – Martijn Pieters Mar 18 '13 at 11:45
  • @MartijnPieters I'm completely new to Python and trying to port some .Net code across - could you give me an example of the proper Python-esque way of doing this? – Basic Mar 18 '13 at 12:02
  • @Basic: That depends entirely on your code base and what you are trying to achieve. It is generally not a good idea to port code between languages one-on-one without experience in the target language, btw. – Martijn Pieters Mar 18 '13 at 12:05
  • @MartijnPieters Tell me about it. I'm aware that I need to make substantial changes in the architecture to take advantage of Python but I've been given a directive that .Net's out and something nix-based is in (Mono isn't an option) We're playing with Java, Python, etc. to see which is the best fit - hence the Q. The classes in question are DTOs that hold a recursive query structure. I'm trying to set up a test case so I can start playing with some code. See the structures here to get an idea... http://stackoverflow.com/questions/15473622/custom-json-deserialisation – Basic Mar 18 '13 at 12:09
  • @Basic: Right, Python rarely (if ever) needs to use DTOs. Use dictionaries or lists or tuples (namedtuple perhaps) instead. Because everything is basically public in Python, there is no need to create getters or setters, removing the need for DTOs. – Martijn Pieters Mar 18 '13 at 12:12
  • @MartijnPieters In this instance, I'm creating an API which gets JSON in one format and has to translate it into another. The DTOs are currently the intermediate stage - Deserialize from FormatA into DTO, Serialize into FormatB. Should I skip the classes entirely then?# – Basic Mar 18 '13 at 12:40
  • 1
    @Basic: Yes, from JSON you'd already have a suitable structure, just serialize to format B from the Python primitives parsed from the JSON . – Martijn Pieters Mar 18 '13 at 12:59

0 Answers0