I’m building classes where I know the intended types of the attributes, but Python of course doesn’t. While it’s un-pythonic to want to tell it, supposing I do want to, is there an idiomatic way to do so?
Why: I’m reading in foreign-format data (without type information) involving objects-nested-inside-objects. It’s easy to put it into nested dictionaries, but I want it in objects of my class-types, to get the right behaviours as well as the data. For instance: suppose my class Book has an attribute isbn which I will fill with an ISBNumber object. My data gives me the isbn as a string; I would like to be able to look at Book and say “That field should be filled by ISBNumber(theString).”
Bonus glee for me if the solution can be applied to classes I get from someone else without editing their code.
(I’m restricted to 2.6, although interested in solutions for 3.x if they exist.)
There are many ways to achieve something like this. If coupling the input format to your object model is acceptable then you could use descriptors to create type adaptors:
However if you don’t fully control the message structure, such coupling isn’t a good idea. In such cases I like to use the interpreter pattern to adapt input messages to output types. I create a small framework that enables me to build declarative object structures to process the input data.
The framework may look something like this:
The message adaptors look something like this:
Notice that the message structure names might not be the same as the object model.
Message processing itself looks like this: