This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author paul.j3
Recipients David.Layton, Paolo.Elvati, Stefan.Pfeiffer, bethard, eric.araujo, manveru, paul.j3
Date 2013-09-23.20:26:03
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <>
In this patch I implement a FileContext class.  It differs from FileType
in 2 key areas:

- it returns a 'partial(open, filename, ...)'
- it wraps '-' (stdin/out) in a dummy context protecting the file from closure.

The resulting argument is meant to be used as:

    with args.input() as f:

The file is not opened until value is called, and it will be closed after the block.  stdin/out can also be used in this context, but without closing.

The signature for this class is the same as for FileType, with one added parameter, 'style'. (alternative name suggestions welcomed).

class argparse.FileContext(mode='r', bufsize=-1, encoding=None, errors=None, style='delayed')

The default behavior, "style='delayed'", is as described above.

"style='evaluate'" immediately calls the partial, returning an opened file.  This is essentially the same as FileType, except for the stdin/out context wrapping.

"style='osaccess'", adds os.acccess testing to determine whether the 'delayed' file can be read or written.  It attempts to catch the same sort of OS errors that  FileType would, but without actually opening or creating the file.

Most of the added tests in copy the FileType tests.  I had to make some modifications to the testing framework to handle the
added levels of indirection.

I have not written the documentation changes yet.

A sample use case is:

    import argparse, sys
    p = argparse.ArgumentParser()
    p.add_argument('-d','--delayed', type=argparse.FileContext('r'))
    p.add_argument('-e','--evaluated', type=argparse.FileContext('r', style='evaluate'))
    p.add_argument('-t','--test', dest='delayed', type=argparse.FileContext('r', style='osaccess'))
    p.add_argument('-o','--output', type=argparse.FileContext('w', style='osaccess'), default='-')
    p.add_argument('--unused', type=argparse.FileContext('w', style='osaccess'),help='unused write file')
    args = p.parse_args()

    with args.output() as o:
        if args.delayed:
            with args.delayed() as f:
                print(, file=o)
        if args.evaluated:
            with args.evaluated as f:
                print(, file=o)
    # f and o will be closed if regular files
    # but not if stdin/out
    # the file referenced by args.unused will not be created
Date User Action Args
2013-09-23 20:26:05paul.j3setrecipients: + paul.j3, bethard, eric.araujo, Paolo.Elvati, manveru, Stefan.Pfeiffer, David.Layton
2013-09-23 20:26:05paul.j3setmessageid: <>
2013-09-23 20:26:04paul.j3linkissue13824 messages
2013-09-23 20:26:04paul.j3create