ctypes, memory mapped files and context manager

Hans-Peter Jansen hpj at urpla.net
Wed Dec 28 17:46:41 EST 2016


On Mittwoch, 28. Dezember 2016 21:58:38 Peter Otten wrote:
> Hans-Peter Jansen wrote:
> > On Mittwoch, 28. Dezember 2016 13:48:48 Peter Otten wrote:
> >> Hans-Peter Jansen wrote:
> > It leaves the question on why is Python2 acting as one would expect
> > related to context managers, and Python3 needs this weakref juggling.
> > Maybe something, that's worth to be placed in python-dev. What do you
> > think?
> 
> Well, given
> 
> $ cat mmap_resize.py
> import ctypes
> import mmap
> 
> class T(ctypes.Structure):
>     _fields_ = [("foo", ctypes.c_uint32)]
> 
> SIZE = 2 * mmap.PAGESIZE
> f = open("tmp.dat", "w+b")
> f.write(b"\0" * SIZE)
> f.seek(0)
> 
> m = mmap.mmap(f.fileno(), SIZE)
> 
> a = T.from_buffer(m, mmap.PAGESIZE)
> m.resize(mmap.PAGESIZE)
> a.foo = 42
> $ python3 mmap_resize.py
> Traceback (most recent call last):
>   File "mmap_resize.py", line 15, in <module>
>     m.resize(mmap.PAGESIZE)
> BufferError: mmap can't resize with extant buffers exported.
> $ python2.7 mmap_resize.py
> Segmentation fault
> 
> do you really prefer the Python 2 behaviour?

Hmm, so Python2 behavior was "working by chance", or better "working without 
any safety net" which isn't the Real McCoy either in that area.

Now, if only the weakref version would behave with the ctypes objects...

Pete


More information about the Python-list mailing list