Subclass str: where is the problem?

harold dadapapa at googlemail.com
Mon Apr 24 10:16:55 EDT 2006


Hi Pascal,

Indeed, the example you show work corrctly. But in the
code you posted before, you wonder about the behavior
of these lines:

> m = MyObject()
> m.id
> ''
> type(m.id)
> <type 'str'>

So what happens when you provide the empty string '' to your and-or
construct?
value = ''
value = type(value) is type('') and Upper(value) or value

As you can easily check, bool('') resolves to False. Thus, your line
becomes:
value = False and False or value
Python first evaluates the and expression, which resolves to False. The
or
expression evaluates the second argument and returns that one as the
result
if and only if the first one evaluates to False, which is the case
here. So the
result of False or value is value. You can check that
>>> value is (False or value)
True
so, in you code, the empty string gets indeed assign as value again.

Be carefull with the condition/and/or chain! You must be 110% sure,
that
the desired return value in case of condition==True can never evaluate
to False!

- harold -




More information about the Python-list mailing list