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~

Attachment: signature.asc
Description: OpenPGP digital signature

_______________________________________________
Python-Dev mailing list
Python-Dev@python.org
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com

Reply via email to