1

Does the Python Standard Library have a standard tool to create a null file object? By this I mean a file object which would not be related to an existing file. It should also behave as a closed file (reading or writing would fail).

Reasoning for the need: I use functions which take opened file as an argument but in certain parameter combinations the file is not being used. Instead of using None value and polluting the code with typing.Optional[] and assert (or even additional if as I think Mypy does not even understand assert!):

def function(arguments: argparse.Namespace, file: typing.Optional[typing.TextIO]) -> None:
    if not arguments.do_not_use_file:
        assert file is not None
        do_something(file)

I would like to use the null file object.

The best way how to create the null file object I was able to find is:

import io

NULL_FILE = io.StringIO()
NULL_FILE.close()

With the null file object the code would be:

def function(arguments: argparse.Namespace, file: typing.TextIO) -> None:
    if not arguments.do_not_use_file:
        do_something(file)

Is there a better way to create the null file object or handle optional file parameters?

  • Is there a reason why you actually want a *closed* file object? Would a well-defined file object such as `/dev/null` also match your purpose? The "better" way is likely not to be in this situation at all – functions working on files ("doing I/O") are usually something else than functions working just by themselves. In other words, ``function`` should not be called in the first place if ``arguments.do_not_use_file`` is false. – MisterMiyagi Jan 27 '21 at 13:35
  • Would overloading your method/function make sense? – gniourf_gniourf Jan 27 '21 at 14:42
  • @MisterMiyagi There are two main reasons why I want a file object not tied to real filesystem entity: 1. security - attempt to use the closed file throws an exception - that is exactly what I want 2. removing unnecessary dependencies and actions (e.g. existence of /dev/null - I guess it would fail e.g. on Windows). --- Separating I/O and processing: I do not think it is really suitable in this case - processing of files with hundreds of thousands lines. Maybe it could be done using generators and coroutines but I do not know coroutines enough yet and I feel over-complication hiding there. – pabouk - Ukraine stay strong Feb 02 '21 at 11:14
  • @gniourf_gniourf Python does not support function overloading or am I missing something? Anyway the function contains the processing code interleaved with I/O operations - overloading the function would need duplication of all the processing code. – pabouk - Ukraine stay strong Feb 02 '21 at 11:26

0 Answers0