What data type should my widgets accept/return?
I'm building a form class in python for producing and validating HTML forms. E开发者_如何学Pythonach field has an associated widget which defines how the field is rendered.
When the widget is created, it is passed in a (default) value so that it knows what to display the first time it is rendered. After the form is submitted, the widget is asked for a value. I delegate this to the widget rather than just nabbing it from the POST data because a widget may consist of several HTML inputs (think of a month/day/year selector). Only the widget knows how to mash these together into one value.
Problem is, I don't know if I should have the widget always accept a string, and always return a string for consistency, or accept and return a data type consistent with its purpose (i.e., a date selector should probably return a DateTime object).
The philosophy behind my form class is "mix and match". You choose what widget you want, and what validators/formatters/converters you want to run on it. Which I guess lends itself towards "use strings" and let the developer decide on the data type afterwords, but... I can't think of a good but. Do you anticipate any problems with this approach?
While simply passing strings around seems like a useful idea, I think you're going to discover it doesn't work as well as you might hope.
Think about the date example—instead of passing around a date
object, instead you pass around a str
of the format "2010-01-01"
. In order to work with that data, every user of the class needs to know not only that it's a str
which represents a date
, but what the format of that string is. In other words, you haven't gained anything. Worse, you lose the ability to pass a datetime
object into the widget (unless you take extra steps to deal with that case).
The validator or formatter issue isn't as big a deal as you might think; how often are you going to want to validate a string which doesn't represent a date as if it were a date?
This approach is quite generic and serializing to and from strings should always work fine. You could also save the state of a widget to a file or send it over a network for recreating another widget from it.
Some potential issues or aspects to consider:
- Localization: how to interpret the string regarding the culture, which format is the canonical format for comparisons.
- Performance: some transformations might be time consuming, but I assume for human interaction that will be far fast enough.
精彩评论