Pipe in the "return" statement

A

Archard Lias

Hi,

I have come across something I don't really understand and would be
grateful if someone could shed some light into my understanding of it.

In the documentation of the Qt4 libs in the page regarding the
QAbstractTableModel you find, to make the table editable, the
following:

Qt::ItemFlags StringListModel::flags(const QModelIndex &index) const
{
if (!index.isValid())
return Qt::ItemIsEnabled;

return QAbstractItemModel::flags(index) | Qt::ItemIsEditable;
}

Now I'm working with PySide, the Python bindings from Nokia and I
figured the
return in the function to be related with a parent
(QAbstractItemModel)
followed by the actual Flag that says: "yes the item, the index is
pointing
at, is actually editable". So translation of the C++ to Python would
be, and
it actually worked:

def flags(self, index):
if not index.isValid():
return Qt.ItemIsEnabled

return super(self.__class__, self).flags(index) |
Qt.ItemIsEditable

Still I dont get how I am supposed to understand the pipe and its task/
idea/influece on control flow, of:
return <statement> | <statement>
??

Thankful if you could help me with this.

Kind regards,
Archard Lias
 
I

Ian Collins

Hi,

Still I dont get how I am supposed to understand the pipe and its task/
idea/influece on control flow, of:
return<statement> |<statement>
??

It's simply a bitwise OR.
 
T

TonyO

Still I dont get how I am supposed to understand the pipe and its task/
idea/influece on control flow, of:
return <statement> | <statement>

In the words of René Magritte,

return <statement> | <statement>
^
Ceci n'est pas une pipe.
 
B

Billy Mays

Yes, but how does it get determined, which one actually gets returned?


The return statement returns a single value from a function context.
The pipe operator takes 2 values and bitwise ORs* them together. That
result is then returned to the caller. The pipe character in this
instance is not the same as in a shell.

* This is not exactly true, but don't worry about it.
 
O

Oliver Bestwalter

J

John Gordon

Yes, but how does it get determined, which one actually gets returned?

Neither value is returned on its own; the bitwise OR of both values is
computed and that value is returned.

It seems that you don't understand what the term "bitwise or" means.
Perhaps a Google search might help.
 
G

gwowen

Yes, but how does it get determined, which one actually gets returned?


It's a bit-wise or, not a logical or so what get returns is a
combination of the two results. The n-th bit of the return value is 1
if the n-th bit of either (or both) of the two statements

(Fixed width font)
a 1 1 0 0 0 1 1 1 0 0 1 0 1 ...
b 0 1 0 1 0 0 1 0 0 0 0 1 1 ...
a|b 1 1 0 1 0 1 1 0 0 0 1 1 1 ...
(/Fixed width font)
 
A

Archard Lias

Hello Archard,




You do a Bitwise OR with numbers. Your statements are both returning numbers and those are combined with a bitwise OR. Combining b0001 with b0010 results in 0011 for example, you can see this very often done in C Code to set and check flags. Here is a gentle introduction:

http://www.codeproject.com/KB/tips/Binary_Guide.aspxhttp://www.codepr...

Cheers
Oliver

Oh!, never gave it a thought about the fact that what I was looking at
where flags... Thank you very much for the link, is a great
introduction to something I had not known before.
 
A

Archard Lias

Neither value is returned on its own; the bitwise OR of both values is
computed and that value is returned.

It seems that you don't understand what the term "bitwise or" means.
Perhaps a Google search might help.

It figures, that you are right :p.
 
A

Archard Lias

Am 25.07.2011 14:00, schrieb Archard Lias:



Your use of super() is incorrect and will not work as you might expect.
You *must* use the class here, never self.__class__.

Christian

It would be great if you could elaborate a little more on that. Am I
not supposed to access the parent here?
 
A

Archard Lias

Am 25.07.2011 17:28, schrieb Archard Lias:


You must spell out the parent explicitly, otherwise subclasses call
super() with themselves rather than the correct parent class.
self.__class__ is too dynamic here. Have a look at this example:

class A(object):
    def method(self):
        pass

class B(A):
    def method(self):
        super(self.__class__, self).method()

class C(B):
    pass

In this example, C().method() results in "super(C, self).method()"
because self.__class__ is C. However that is wrong because you have to
call super() with the direct parent.

Christian

Oh! Get it, thanks a lot :p
 
E

Ethan Furman

Billy said:
The return statement returns a single value from a function context. The
pipe operator takes 2 values and bitwise ORs* them together. That
result is then returned to the caller.

Just for completeness, if the actual line had been

return <statement1> or <statement2>

then Python would compute <statement1>, and if its boolean value was
True would return the computation of <statement1>, otherwise it would
compute <statement2> and return that. When 'or' is used, the first
truthy* item is return, or the last falsey* item if none evaluate to True.

--> None or 2 or 0
2
--> None or 2 or 3
2
--> None or [] or 0
0

With 'and', the first falsey item is returned, unless all the items are
truthy in which case the last item is returned:

--> 2 and 3
3
--> 2 and 0 and 9
0

Hope this helps.

~Ethan~

* 'truthy' = bool(some expression or object) == True
* 'falsey' = bool(some expression or object) == False
 
S

Sells, Fred

I'm tring to unzip a buffer that is uploaded to django/python. I can
unzip the file in batch mode just fine, but when I get the buffer I get
a "BadZipfile exception. I wrote this snippet to try to isolate the
issue but I don't understand what's going on. I'm guessing that I'm
losing some header/trailer somewhere?

def unittestZipfile(filename):
buffer = ''
f = open(filename)
for i in range(22):
block = f.read()
if len(block) == 0:
break
else:
buffer += block

print len(buffer)
tmp = open('tmp.zip', 'w')
tmp.write(buffer)
tmp.close()
zf = zipfile.ZipFile('tmp.zip')
print dir(zf)
for name in zf.namelist():
print name
print zf.read(name)
____________________________________________________________
2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit (Intel)]
Traceback (most recent call last):
File
"C:\all\projects\AccMDS30Server\mds30\app\uploaders\xmitzipfile.py",
line 162, in <module>
unittestZipfile('wk1live7.8to7.11.zip')
File
"C:\all\projects\AccMDS30Server\mds30\app\uploaders\xmitzipfile.py",
line 146, in unittestZipfile
print zf.read(name)
File "C:\alltools\python26\lib\zipfile.py", line 837, in read
return self.open(name, "r", pwd).read()
File "C:\alltools\python26\lib\zipfile.py", line 867, in open
raise BadZipfile, "Bad magic number for file header"
zipfile.BadZipfile: Bad magic number for file header
 
B

Billy Mays

I'm tring to unzip a buffer that is uploaded to django/python. I can
unzip the file in batch mode just fine, but when I get the buffer I get
a "BadZipfile exception. I wrote this snippet to try to isolate the
issue but I don't understand what's going on. I'm guessing that I'm
losing some header/trailer somewhere?

def unittestZipfile(filename):
buffer = ''
f = open(filename)
for i in range(22):
block = f.read()
if len(block) == 0:
break
else:
buffer += block

print len(buffer)
tmp = open('tmp.zip', 'w')
tmp.write(buffer)
tmp.close()
zf = zipfile.ZipFile('tmp.zip')
print dir(zf)
for name in zf.namelist():
print name
print zf.read(name)
____________________________________________________________
2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit (Intel)]
Traceback (most recent call last):
File
"C:\all\projects\AccMDS30Server\mds30\app\uploaders\xmitzipfile.py",
line 162, in<module>
unittestZipfile('wk1live7.8to7.11.zip')
File
"C:\all\projects\AccMDS30Server\mds30\app\uploaders\xmitzipfile.py",
line 146, in unittestZipfile
print zf.read(name)
File "C:\alltools\python26\lib\zipfile.py", line 837, in read
return self.open(name, "r", pwd).read()
File "C:\alltools\python26\lib\zipfile.py", line 867, in open
raise BadZipfile, "Bad magic number for file header"
zipfile.BadZipfile: Bad magic number for file header

You need to specify the file mode since I'm guessing you use Windows
from the traceback:

f = open(filename, 'rb')

and later:

tmp = open('tmp.zip', 'wb')
 
P

Peter Otten

I'm tring to unzip a buffer that is uploaded to django/python. I can
unzip the file in batch mode just fine, but when I get the buffer I get
a "BadZipfile exception. I wrote this snippet to try to isolate the
issue but I don't understand what's going on. I'm guessing that I'm
losing some header/trailer somewhere?

Why are you copying the file before you try to unzip it?
def unittestZipfile(filename):
buffer = ''
f = open(filename)

Open the file in binary mode:

f = open(filename, "rb")
for i in range(22):
block = f.read()
if len(block) == 0:
break
else:
buffer += block
print len(buffer)
tmp = open('tmp.zip', 'w')

Again, open the file in binary mode ("wb").
tmp.write(buffer)
tmp.close()

Not essential to the problem you are encountering, but you want
shutil.copyfile(). Also, have a look at the shutil.copyfileobj()
implementation to learn how to properly copy a file in chunks of limited
size.
zf = zipfile.ZipFile('tmp.zip')
print dir(zf)
for name in zf.namelist():
print name
print zf.read(name)
____________________________________________________________
2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit (Intel)]
Traceback (most recent call last):
File
"C:\all\projects\AccMDS30Server\mds30\app\uploaders\xmitzipfile.py",
line 162, in <module>
unittestZipfile('wk1live7.8to7.11.zip')
File
"C:\all\projects\AccMDS30Server\mds30\app\uploaders\xmitzipfile.py",
line 146, in unittestZipfile
print zf.read(name)
File "C:\alltools\python26\lib\zipfile.py", line 837, in read
return self.open(name, "r", pwd).read()
File "C:\alltools\python26\lib\zipfile.py", line 867, in open
raise BadZipfile, "Bad magic number for file header"
zipfile.BadZipfile: Bad magic number for file header
 
S

Sells, Fred

Thanks all, adding the 'rb' and 'wb' solved that test case.

The reason I read the file "the hard way" is that I'm testing why I
cannot unzip a buffer passed in a file upload using django.

While not actually using a file, pointing out the need for the binary
option gave me the clue I needed to upload the file

All is good and moving on to the next crisis ;)

Fred.
 
T

Thomas 'PointedEars' Lahn

Ethan said:
Just for completeness, if the actual line had been

return <statement1> or <statement2>

then Python would compute <statement1>, and if its boolean value was
True would return the computation of <statement1>, otherwise it would
compute <statement2> and return that. When 'or' is used, the first
truthy* item is return, or the last falsey* item if none evaluate to True.

Hence "*bitwise* OR" (as Billy wrote), _not_ logical OR (as you wrote),
probably.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top