[Tutor] Changing the Attribute of a Variable

Martin Walsh mwalsh at mwalsh.org
Wed Feb 18 12:19:13 CET 2009


Marc Tompkins wrote:
> Also - config_var_list is a tuple of lists.  (I'm guessing you intended
> to make it a list of lists - that's what the name indicates, after all -
> but putting it between "( )" makes it a tuple.)  

Sound advice, but a subtle clarification is warranted I think. It's the
comma(s) that make a tuple not the parens (and an absence of square
brackets, I suppose). Consider the following:

In [1]: a = (1)

In [2]: a
Out[2]: 1

In [3]: type(a)
Out[3]: <type 'int'>

In [4]: b = (1,)

In [5]: b
Out[5]: (1,)

In [6]: type(b)
Out[6]: <type 'tuple'>

In [7]: c = 1, 2, 3

In [8]: c
Out[8]: (1, 2, 3)

In [9]: type(c)
Out[9]: <type 'tuple'>

...

Wayne, I second Marc's advice that you're making it hard on yourself.
Understandable to a degree, if you are trying to avoid major
modification to inherited code.

But, loading and saving configuration data is a 'solved' problem in that
there are many choices of ready-made tools to help you accomplish the
task. And, I don't see anything in your description that would indicate
a custom solution is necessary -- except perhaps for the learning
experience, almost never a bad idea, IMHO.

Marc has already pointed out ConfigObj, which is excellent, but I
thought I would also suggest ConfigParser -- part of the standard lib,
if a bit less feature-full.

Back to your original question, and I'm probably overstating the obvious
at this point, but the underlying problem is that the operation causing
the exception is expecting a datetime.time object and getting a str. So,
it's less about adding a strftime attribute to the str object, and more
about 'converting' the str into a datetime.time object.

Short of re-writing for ConfigObj (which provides a type conversion and
validation mechanism), or pickle, or similar -- you'll need to work out
how to convert between str and datetime.time. Here are some (untested)
examples:

def time_to_str(t):
    return t.strftime('%H:%M:%S')

def str_to_time(s):
    h, m, s = [int(u) for u in s.split(':')]
    return datetime.time(h, m, s)

HTH,
Marty

PS. You can avoid posting images of tracebacks by enabling 'Quick Edit'
mode in your windows command prompt. More info here:
http://support.microsoft.com/kb/282301



More information about the Tutor mailing list