[docs] [issue13424] Add examples for open’s new opener argument

Serhiy Storchaka report at bugs.python.org
Sun Nov 4 12:09:55 CET 2012


Serhiy Storchaka added the comment:

Isn't it be clearer?

      >>> import os
      >>> dir_fd = os.open('somedir', os.O_RDONLY)
      >>> def opener(path, flags):
      ...     return os.open(path, flags, dir_fd=dir_fd)
      ...
      >>> with open('spamspam.txt', 'w', opener=opener) as f:
      ...     print('This will be written to somedir/spamspam.txt', file=f)
      ...
      >>> os.close(dir_fd)  # don't leak a file descriptor

Or if you want stronger example:

      >>> import os, contextlib, functools
      >>> @contextlib.contextmanager
      ... def open_relative(dirname):
      ...     dir_fd = os.open(dirname, os.O_RDONLY)
      ...     def opener(path, flags):
      ...         return os.open(path, flags, dir_fd=dir_fd)
      ...     try:
      ...         yield functools.partial(open, opener=opener)
      ...     finally:
      ...         os.close(dir_fd)
      ...
      >>> with open_relative('somedir') as open:
      ...     with open('spamspam.txt', 'w') as f:
      ...         print('This will be written to somedir/spamspam.txt', file=f)
      ...

Frankly speaking, all of these examples looks unconvincing to me.  Even the second example could be implemented without an "opener" argument.

----------

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue13424>
_______________________________________


More information about the docs mailing list