[Python-Dev] boxing and unboxing data types
Ethan Furman
ethan at stoneleaf.us
Mon Mar 9 04:31:30 CET 2015
When data is passed from Python to a native library (such as in an O/S call), how does the unboxing of data types occur?
For a specific instance, os.open allows an integer whose various bits express desired behavior as `flags` -- if flags is
1, for example, the file is open write-only.
If I pass an int-like object to os.open, __int__ is called; if I pass a thin wrapper over int to os.open, __int__ is not
called.
So the real question: anywhere in Python where an int is expected (for lower-level API work), but not directly
received, should __int__ (or __index__) be called? and failure to do so is a bug?
Here's my simple test code:
class Wrap:
def __init__(self, value):
self.value = value
def __int__(self):
print('__int__')
return self.value
def __index__(self):
print('__index__')
return self.value
class Thin(int):
def __int__(self):
print('__int__')
return super().__int__()
def __index__(self):
print('__index__')
return super().__index__()
two = Wrap(2)
[0, 1, 2][two]
# __index__
# 2
import struct
struct.pack('i', two)
# __index__
# b'\x02\x00\x00\x00'
t = Thin(1)
huh = os.open('blah.txt', t)
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# FileNotFoundError: [Errno 2] No such file or directory: 'blah.txt'
--
~Ethan~
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 836 bytes
Desc: OpenPGP digital signature
URL: <http://mail.python.org/pipermail/python-dev/attachments/20150308/53685c73/attachment.sig>
More information about the Python-Dev
mailing list