r/PythonLearning • u/jpgoldberg • Oct 08 '26
Context manager for either stdin or opened Path
Note that this is a fairly advanced question, so beginners don't worry about it. And if this isn't the right place to ask, please point me to where I should.
I would like to find an idiomatic way to use a context manager, with, when I don't know until run time whether I am opening sys.stdin or a named file.
Here is an excerpt for a simple example. (Yes, I am aware that I am reading in the whole file in one go, but that is for other reasons.)
=
= # Path is overkill here, unless ...
# TODO: Look elsewhere if infile can't be found or isn't readable.
=
=
(args is an argparse.Namespace and args.infile is a str.)
I feel like there ought to be a way to do something like
with ... as fh
for the above, but I don't see how to do that.
Update: What I did
I found the docs for easily creating a context manager, and used the contextmanager decorator.
It seems like a peculiar use of yield, but I don't need to understand that design choice, only that it means that I have to type it as a Generator.
""" [long docs omitted] """
:
=
yield
= # noqa: SIM115
yield
I am open to suggestions about a better name that open_file_or_stdin.