473,466 Members | 1,445 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Subclass str: where is the problem?

Hello, can anybody explain/help me:

Python 2.4.2 (#2, Sep 30 2005, 21:19:01)
[GCC 4.0.2 20050808 (prerelease) (Ubuntu 4.0.1-4ubuntu8)] on linux2
class Upper(str):
def __new__(cls, value):
return str.__new__(cls, value.upper())

u = Upper('test')
u
'TEST'
type(u)
<class '__main__.Upper'>
u = Upper('')
u
''
type(u)
<class '__main__.Upper'>
All seems to be ok...

class MyObject(object):
def __init__(self, dictionary = {}):
self.id = dictionary.get('id', '')
def __setattr__(self, attribute, value):
value = type(value) is type('') and Upper(value) or value
object.__setattr__(self, attribute, value)

m = MyObject({'id': 'test'})
m.id
'TEST'
type(m.id)
<class '__main__.Upper'>
m = MyObject()
m.id
''
type(m.id)
<type 'str'>

Why is m.id a str ?
Thanks.

Apr 24 '06 #1
5 1065

pa***********@free.fr schrieb:
Hello, can anybody explain/help me:

Python 2.4.2 (#2, Sep 30 2005, 21:19:01)
[GCC 4.0.2 20050808 (prerelease) (Ubuntu 4.0.1-4ubuntu8)] on linux2
class Upper(str):
def __new__(cls, value):
return str.__new__(cls, value.upper())

u = Upper('test')
u
'TEST'
type(u)
<class '__main__.Upper'>
u = Upper('')
u
''
type(u)
<class '__main__.Upper'>
All seems to be ok...

class MyObject(object):
def __init__(self, dictionary = {}):
self.id = dictionary.get('id', '')
def __setattr__(self, attribute, value):
value = type(value) is type('') and Upper(value) or value
object.__setattr__(self, attribute, value)

m = MyObject({'id': 'test'})
m.id
'TEST'
type(m.id)
<class '__main__.Upper'>
m = MyObject()
m.id
''
type(m.id)
<type 'str'>

Why is m.id a str ?
Because Upper(value) will be False in the line value = type(value) is type('') and Upper(value) or value

and thus, you assign value itself to value again.
rewrite it for exmaple in this way:

def __setattr__(self, attribute, value):
if type(value) is type('') :
value = Upper(value)
object.__setattr__(self, attribute, value)

Apr 24 '06 #2
This is good... try this:

value = 'test'
value
'test'
type(value)
<type 'str'>
value = type(value) is type('') and Upper(value) or value
value
'TEST'
type(value)
<class '__main__.Upper'>

value = 1
value
1
type(value)
<type 'int'>
value = type(value) is type('') and Upper(value) or value
value
1
type(value)
<type 'int'>

Apr 24 '06 #3
pa***********@free.fr wrote:
This is good... try this:

value = 'test'
value
'test'
type(value)
<type 'str'>
value = type(value) is type('') and Upper(value) or value
value
'TEST'
type(value)
<class*'__main__.Upper'>


Try again with

value = ""

This makes Upper(value) a False value in a boolean context:
class Upper(str): .... pass
.... Upper("") '' type(Upper("")) <class '__main__.Upper'> type(Upper("") or "") <type 'str'>

versus
type(Upper("x") or "x")

<class '__main__.Upper'>

Peter

Apr 24 '06 #4
Effectively.
Thanks a lot Peter and Harold.

Apr 24 '06 #5
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 -

Apr 24 '06 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Kenneth McDonald | last post by:
I'm attempting to create a subclass of 'str' that I can abitrarily initialize at creation time. As an illustration, this gives the flavor of what I'm trying to do: class AlwaysLower(str): def...
4
by: MyndPhlyp | last post by:
I am working with Classes in classic VBScript on IIS 5.0 and am having a problem wrapping my head around a solution. I have a Class defining a record layout. (Bear with me here as I completely...
0
bartonc
by: bartonc | last post by:
from MySQLdb import * from time import time class DBServer: def __init__(self, master): self.master = master def Login(self, servername, username, password): #,...
9
by: Mark Morss | last post by:
I would like to construct a class that includes both the integers and None. I desire that if x and y are elements of this class, and both are integers, then arithmetic operations between them,...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.