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?