473,327 Members | 1,892 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,327 software developers and data experts.

The curious behavior of integer objects

Am I nuts? Or only profoundly confused? I expected the this little script
to print "0":

class foo(int):
def __init__(self, value):
self = value & 0xF

print foo(0x10)

Instead, it prints "16" (at least on python 2.4.4 (Linux) and 2.5 (Wine).

Jim Wilson
GNV, FL
Jan 15 '07 #1
15 1353
As it turns out, this has little to do with integers and the
operations you are trying to do on them. I'll explain in more detail.

Integers are immutable, which you may already know. This presents a
problem with subclassing them and using the usual special method
__init__, because the int object has already been created by this
point and can not change. Another special method, __new__, is called
passing the class object itself (foo, in this case) for the first
argument (traditionally named cls, instead of self). The return of
this should be an integer which will be the value of your new foo
int-subclass.

The following will do as you expected your own example to do.

class foo(int):
def __new__(cls, value):
return value & 0xF

assert foo(0x10) == 0 # Assertions are much better tests than prints :-)

On 1/15/07, Jim B. Wilson <wi****@afn.orgwrote:
Am I nuts? Or only profoundly confused? I expected the this little script
to print "0":

class foo(int):
def __init__(self, value):
self = value & 0xF

print foo(0x10)

Instead, it prints "16" (at least on python 2.4.4 (Linux) and 2.5 (Wine).

Jim Wilson
GNV, FL
--
http://mail.python.org/mailman/listinfo/python-list

--
Read my blog! I depend on your acceptance of my opinion! I am interesting!
http://ironfroggy-code.blogspot.com/
Jan 15 '07 #2
Jim B. Wilson wrote:
Am I nuts? Or only profoundly confused? I expected the this little script
to print "0":

class foo(int):
def __init__(self, value):
self = value & 0xF
That statement only rebinds the local name self to something else. It does not
modify the object at all or change the result of instantiating foo(). You need
to override __new__ to get the behavior that you want.

http://www.python.org/download/relea...intro/#__new__

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco

Jan 15 '07 #3
At Monday 15/1/2007 19:28, Jim B. Wilson wrote:
>Am I nuts? Or only profoundly confused? I expected the this little script
to print "0":

class foo(int):
def __init__(self, value):
self = value & 0xF

print foo(0x10)

Instead, it prints "16" (at least on python 2.4.4 (Linux) and 2.5 (Wine).
Integers are immutable. Insert a print statement and you'll see your
__init__ is never called. Anyway, what would you expect from "self =
something"?
Use __new__ instead:

pyclass foo(int):
.... def __new__(cls, value):
.... return int(value & 0xF)
....
pyfoo(1)
1
pyfoo(0x10)
0

See "Special method names" inside the Python Reference Manual.
--
Gabriel Genellina
Softlab SRL


__________________________________________________
Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya!
http://www.yahoo.com.ar/respuestas

Jan 15 '07 #4
On Mon, 15 Jan 2007 17:50:56 -0500, Calvin Spealman wrote:
assert foo(0x10) == 0 # Assertions are much better tests than prints :-)
I dispute that assertion (pun intended).

Firstly, print statements work even if you pass the -O (optimize) flag
to Python. Your asserts don't.

Secondly, a bare assertion like that gives you very little information: it
just tells you that it failed:
>>x = 1
assert x == 0
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AssertionError

To provide the same information that print provides, you need something
like this:

assert x == 0, "x == %s not 0" % x

Thirdly, and most importantly, assert and print aren't alternatives,
but complementary tools. Assertions are good for automated testing and
simple data validation, where you already know what values you should
have. Printing is good for interactively exploring your data when you're
uncertain about the values you might get: sometimes it is hard to know
what you should be asserting until you've seen what results your function
returns.

--
Steven D'Aprano

Jan 16 '07 #5
On 1/15/07, Steven D'Aprano <st***@removeme.cybersource.com.auwrote:
On Mon, 15 Jan 2007 17:50:56 -0500, Calvin Spealman wrote:
assert foo(0x10) == 0 # Assertions are much better tests than prints :-)

I dispute that assertion (pun intended).
Hah!
Firstly, print statements work even if you pass the -O (optimize) flag
to Python. Your asserts don't.
This is true, but the concept can be adapted to a things like an
assert_() function.
Secondly, a bare assertion like that gives you very little information: it
just tells you that it failed:
>x = 1
assert x == 0
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AssertionError

To provide the same information that print provides, you need something
like this:

assert x == 0, "x == %s not 0" % x
What information would I need to know if my test passed? Nothing, I
say. I only want to know when the tests fail, especially as I add more
of them. Having no output is a great way to know nothing puked.
Thirdly, and most importantly, assert and print aren't alternatives,
but complementary tools. Assertions are good for automated testing and
simple data validation, where you already know what values you should
have. Printing is good for interactively exploring your data when you're
uncertain about the values you might get: sometimes it is hard to know
what you should be asserting until you've seen what results your function
returns.
True, but I intended my statement as a nudge towards more proper
testing. Even when testing things out, I often use an assert rather
than a print, to verify some condition.
--
Steven D'Aprano

--
http://mail.python.org/mailman/listinfo/python-list

--
Read my blog! I depend on your acceptance of my opinion! I am interesting!
http://ironfroggy-code.blogspot.com/
Jan 16 '07 #6
Calvin Spealman wrote:
On 1/15/07, Steven D'Aprano <st***@removeme.cybersource.com.auwrote:
>On Mon, 15 Jan 2007 17:50:56 -0500, Calvin Spealman wrote:
>>assert foo(0x10) == 0 # Assertions are much better tests than prints :-)
I dispute that assertion (pun intended).

Hah!
>Firstly, print statements work even if you pass the -O (optimize) flag
to Python. Your asserts don't.

This is true, but the concept can be adapted to a things like an
assert_() function.
>Secondly, a bare assertion like that gives you very little information: it
just tells you that it failed:
>>>>x = 1
assert x == 0
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AssertionError

To provide the same information that print provides, you need something
like this:

assert x == 0, "x == %s not 0" % x

What information would I need to know if my test passed? Nothing, I
say. I only want to know when the tests fail, especially as I add more
of them. Having no output is a great way to know nothing puked.
>Thirdly, and most importantly, assert and print aren't alternatives,
but complementary tools. Assertions are good for automated testing and
simple data validation, where you already know what values you should
have. Printing is good for interactively exploring your data when you're
uncertain about the values you might get: sometimes it is hard to know
what you should be asserting until you've seen what results your function
returns.

True, but I intended my statement as a nudge towards more proper
testing. Even when testing things out, I often use an assert rather
than a print, to verify some condition.
There have been times where I would like assert to be a little more assertive
than it is. :-)

ie.. not being able to turn them off with the -0/-00 switches, and having them
generate a more verbose traceback.

Maybe have an alternative 'warn' as an alternative debugging version that could
be set to ignore, soft (print to log), and hard (raise an error).

An assert statement is a little clearer than an if...raise... in cases where you
want to raise a value exception of some type. But I'm probably in the minority
on this one.

Ron






Jan 16 '07 #7
On Mon, 15 Jan 2007 21:38:42 -0500, Calvin Spealman wrote:
On 1/15/07, Steven D'Aprano <st***@removeme.cybersource.com.auwrote:
>On Mon, 15 Jan 2007 17:50:56 -0500, Calvin Spealman wrote:
assert foo(0x10) == 0 # Assertions are much better tests than prints :-)

I dispute that assertion (pun intended).

Hah!
>Firstly, print statements work even if you pass the -O (optimize) flag
to Python. Your asserts don't.

This is true, but the concept can be adapted to a things like an
assert_() function.
Hence defeating the optimization :)

So what you're saying is, some custom function that you write yourself is
better than print? I suppose I can't argue with that :)

>Secondly, a bare assertion like that gives you very little information:
it just tells you that it failed:
>>x = 1
assert x == 0
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AssertionError

To provide the same information that print provides, you need something
like this:

assert x == 0, "x == %s not 0" % x

What information would I need to know if my test passed? Nothing, I say.
Maybe. But then it is hard to tell the difference between "my test
function printed nothing because it is broken, and my test function
printed nothing because it succeeded".

There are good arguments both for and against successful tests printing a
result. Keep in mind that a successful assert doesn't actually print
"nothing" in the interactive interpreter: when it completes, you do get
feedback because Python prints a prompt. Getting feedback that the test
completed successfully is vital. The only question is whether that
feedback should be minimal or verbose.

But in any case, you have misunderstood the assertion. The error message
is printed *if the assert fails*, not if it passes.

I only want to know when the tests fail, especially as I add more of
them. Having no output is a great way to know nothing puked.
Sure -- for unit testing. For interactive exploration, seeing the value of
a variable is better than guessing. That's why a bare object reference in
the interactive interpreter prints itself, but in a script does nothing.

--
Steven D'Aprano

Jan 16 '07 #8
On 1/15/07, Steven D'Aprano <st***@removeme.cybersource.com.auwrote:
On Mon, 15 Jan 2007 21:38:42 -0500, Calvin Spealman wrote:
On 1/15/07, Steven D'Aprano <st***@removeme.cybersource.com.auwrote:
On Mon, 15 Jan 2007 17:50:56 -0500, Calvin Spealman wrote:

assert foo(0x10) == 0 # Assertions are much better tests than prints :-)

I dispute that assertion (pun intended).
Hah!
Firstly, print statements work even if you pass the -O (optimize) flag
to Python. Your asserts don't.
This is true, but the concept can be adapted to a things like an
assert_() function.

Hence defeating the optimization :)

So what you're saying is, some custom function that you write yourself is
better than print? I suppose I can't argue with that :)

Secondly, a bare assertion like that gives you very little information:
it just tells you that it failed:

x = 1
assert x == 0
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AssertionError

To provide the same information that print provides, you need something
like this:

assert x == 0, "x == %s not 0" % x
What information would I need to know if my test passed? Nothing, I say.

Maybe. But then it is hard to tell the difference between "my test
function printed nothing because it is broken, and my test function
printed nothing because it succeeded".

There are good arguments both for and against successful tests printing a
result. Keep in mind that a successful assert doesn't actually print
"nothing" in the interactive interpreter: when it completes, you do get
feedback because Python prints a prompt. Getting feedback that the test
completed successfully is vital. The only question is whether that
feedback should be minimal or verbose.

But in any case, you have misunderstood the assertion. The error message
is printed *if the assert fails*, not if it passes.

I only want to know when the tests fail, especially as I add more of
them. Having no output is a great way to know nothing puked.

Sure -- for unit testing. For interactive exploration, seeing the value of
a variable is better than guessing. That's why a bare object reference in
the interactive interpreter prints itself, but in a script does nothing.
1) I was trying to nudge the OP towards unit testing
2) if you look at the printed verson of an object you are as much
guessing as you would with an assert and no output
3) It was just an arbitrary statement and although I stand by it, is
it worth this much discussion?
--
Steven D'Aprano

--
http://mail.python.org/mailman/listinfo/python-list

--
Read my blog! I depend on your acceptance of my opinion! I am interesting!
http://ironfroggy-code.blogspot.com/
Jan 16 '07 #9
On Mon, 15 Jan 2007 21:01:35 -0600, Ron Adam wrote:

There have been times where I would like assert to be a little more assertive
than it is. :-)

ie.. not being able to turn them off with the -0/-00 switches, and having them
generate a more verbose traceback.
If you want something more verbose, you have it:
>>assert False, "verbose traceback"
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AssertionError: verbose traceback

If you want something that won't be turned off by -O, you maybe need to
write your own:

def assert_(condition, msg=""):
if not condition:
raise AssertionError(msg)
Maybe have an alternative 'warn' as an alternative debugging version that could
be set to ignore, soft (print to log), and hard (raise an error).
Check out the warnings module.
--
Steven D'Aprano

Jan 16 '07 #10
Steven D'Aprano wrote:
On Mon, 15 Jan 2007 21:01:35 -0600, Ron Adam wrote:

>There have been times where I would like assert to be a little more assertive
than it is. :-)

ie.. not being able to turn them off with the -0/-00 switches, and having them
generate a more verbose traceback.

If you want something more verbose, you have it:
>>>assert False, "verbose traceback"
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AssertionError: verbose traceback

If you want something that won't be turned off by -O, you maybe need to
write your own:

def assert_(condition, msg=""):
if not condition:
raise AssertionError(msg)
>Maybe have an alternative 'warn' as an alternative debugging version that could
be set to ignore, soft (print to log), and hard (raise an error).

Check out the warnings module.
Yes, I know it's there. It just seems like assert and warn() overlap currently.
Assert doesn't quite fill warn()'s shoes, and warn() isn't as unassertive as
assert when it's turned off.

A warn statement could be completely ignored and not even cost a function call
when it's turned off like assert does now. I don't think it does that
currently. Isn't there always some overhead when using the warn() function. Or
is there some magic there?

An if-raise is just as fast as assert when evaluating as True, so there's no
speed advantage there unless you have a large percentage of raises. But it does
looks a lot nicer when you want a short positive test, verses a longer negative
test with a raise stuck on it.

But I think the developers would not consider this to be a big enough matter to
be worth changing. So I'll continue to ignore warn(), and also continue to be
un-assertive in my python code.

Cheers,
Ron

Jan 16 '07 #11
Ron Adam wrote:
There have been times where I would like assert to be a little more assertive
than it is. :-)

ie.. not being able to turn them off with the -0/-00 switches, and having them
generate a more verbose traceback.
Personally, I'd rather see it get less assertive, i.e., having it only
work in a special debugging mode. That way people who haven't RTFM
don't use it to make sure their input is correct.
Carl Banks

Jan 16 '07 #12
Carl Banks wrote:
Ron Adam wrote:
>There have been times where I would like assert to be a little more assertive
than it is. :-)

ie.. not being able to turn them off with the -0/-00 switches, and having them
generate a more verbose traceback.

Personally, I'd rather see it get less assertive, i.e., having it only
work in a special debugging mode. That way people who haven't RTFM
don't use it to make sure their input is correct.
Carl Banks
Well, the manual could be improved in this area quite a bit. There also really
need to be easier to find examples for both assert and warnings use.
But it does only work in a special debugging mode. Didn't you RTFM? ;-)

http://docs.python.org/ref/assert.html

It just happens this mode is turned on by default. So you would like this to be
turned off by default. I agree. I think there may be a way to change pythons
default startup behavior for this.
Warnings generated by warn() on the other hand can be silenced, but not
completely ignored. But I also think they could be a more useful and flexible
tool for debugging purposes.

http://docs.python.org/lib/warning-functions.html

I have to admit that part of why assert seems wrong to me is the meaning of the
word implies something you shouldn't be able to ignore. While warnings seem
like something that can be disregarded.

I think maybe the best way to use both may be to combine them...

assert <conditionwarn(...)

But I'm not sure that doesn't have problems of it's own. <shrug>

Cheers,
Ron




Jan 16 '07 #13
On 2007-01-16, Ron Adam <rr*@ronadam.comwrote:
I have to admit that part of why assert seems wrong to me is
the meaning of the word implies something you shouldn't be able
to ignore. While warnings seem like something that can be
disregarded.
Experienced C coders expect assert to behave like that.

The only reason (I know of) to turn off error checking is to
optimize. However, removing tests won't usually make a big enough
speed difference to be worth the burthen of testing two different
versions of the same source code.

So to me the assert statement is either dubious syntax-sugar or
dangerous, depending on Python's command line arguments.

The warning module would seem to have limited applications.
Searching my Python distribution shows that it's used for
deprecation alerts, and elsewhere for turning those selfsame
alerts off. How copacetic! It is the null module. ;-)

--
Neil Cerutti
Facts are stupid things. --Ronald Reagan
Jan 16 '07 #14
Neil Cerutti wrote:
On 2007-01-16, Ron Adam <rr*@ronadam.comwrote:
>I have to admit that part of why assert seems wrong to me is
the meaning of the word implies something you shouldn't be able
to ignore. While warnings seem like something that can be
disregarded.

Experienced C coders expect assert to behave like that.

The only reason (I know of) to turn off error checking is to
optimize. However, removing tests won't usually make a big enough
speed difference to be worth the burthen of testing two different
versions of the same source code.
Ah... but that's the irony. The whole purpose of the existence of the second
version you refer to, is to better check the first version. These checks should
not change the flow of code that is executed!

The problem with assert as a debugging tool, is it *can* change the execution
flow by raising a catchable exception. So you do have *two* versions that may
not behave the same.

Like I suggested earlier, assert should not be turned off *ever*, but should be
considered a nicer way to generate exceptions to do value checks.

And warnings should never change code execution order, but we should be able to
completely turn them off on the byte code level like asserts are when the -O
command line option is given.

I believe both of these features would be used a lot more if they where like this.

So to me the assert statement is either dubious syntax-sugar or
dangerous, depending on Python's command line arguments.
Yep.. unless you use them in a very limited way.

The warning module would seem to have limited applications.
Searching my Python distribution shows that it's used for
deprecation alerts, and elsewhere for turning those selfsame
alerts off. How copacetic! It is the null module. ;-)
I think you understand the point I'm trying to make. :-)

Ron

Jan 16 '07 #15

Neil Cerutti wrote:
On 2007-01-16, Ron Adam <rr*@ronadam.comwrote:
I have to admit that part of why assert seems wrong to me is
the meaning of the word implies something you shouldn't be able
to ignore. While warnings seem like something that can be
disregarded.

Experienced C coders expect assert to behave like that.

The only reason (I know of) to turn off error checking is to
optimize. However, removing tests won't usually make a big enough
speed difference to be worth the burthen of testing two different
versions of the same source code.
I don't know about you, but I tend put very expensive checks in assert
statements (or inside an if __debug__). Stuff like checking one-to-one
synchronicity between two large trees, checking whether lists are
sorted, etc. If all you're doing is asserting that x==0, yeah, who
cares. If you're asserting issorted(list), I think you might want to
shut that off in production code.

So to me the assert statement is either dubious syntax-sugar or
dangerous, depending on Python's command line arguments.
If used as intended (i.e., to claim that a correct program should
always meet the condition), it shouldn't be any more dangerous than
omitting the test altogether.

The danger comes from using it to check for things that aren't
indicative of a bug in the program; for instance, to verify input.
Then the program can crash and burn if optimization is turned on.
Carl Banks

Jan 16 '07 #16

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

Similar topics

9
by: Xiangliang Meng | last post by:
The fragment code: #include <iostream> using namespace std; class Integer { int i; public: Integer() : i(0) {};
4
by: Oz | last post by:
This is long. Bear with me, as I will really go through all the convoluted stuff that shows there is a problem with streams (at least when used to redirect stdout). The basic idea is that my...
40
by: Confused User | last post by:
I am curious what the origins of size_t are. I see that it is usually typedef'd to be the native integer size of a particular machine. I also see that routines like strncpy(char *t, const char *s,...
3
by: Arnold Schrijver | last post by:
I wrote a program that draws items to the screen and maintains a set of Offset values. There was a bug in the code, because objects were positioned wrongly. While debugging I found some peculiar...
1
by: lists | last post by:
When using the (tbl).field notation for selecting a specific field from a composite field then the query returning the field is executed once per field. An example is giving below. The runtime is...
30
by: questions? | last post by:
say I have a structure which have an array inside. e.g. struct random_struct{ char name; int month; } if the array is not intialized by me, in a sense after I allocated a
4
by: neo | last post by:
I made a console based application in vs2k5. I made a class with the name "A" which has one function with the name of "function" and has one member integer variable initialized with 99; its code is...
6
by: =?Utf-8?B?TWljaGVsIFBvc3NldGggW01DUF0=?= | last post by:
Hello i just encountered a funny situation Dim i As Integer = 0 MsgBox(i = Nothing) and
33
by: coolguyaroundyou | last post by:
Will the following statement invoke undefined behavior : a^=b,b^=a,a^=b ; given that a and b are of int-type ?? Be cautious, I have not written a^=b^=a^=b ; which, of course, is undefined....
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you

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.