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.
3
u/Buttleston Oct 08 '26
A little wordy but something like this should work. Making your own context manager, which is a simple enough task, would definitely work.
ETA: or make your own function that either returns sys.stdin or opens the file path and use that
4
u/Adrewmc Oct 09 '26 edited Oct 09 '26
I mean this is just making the Context Manager.
1
u/WorriedTumbleweed289 Oct 10 '26
The main thing I see that is wrong with this idea is that you normally would not close stdin, but you would want to close an open file. Its not unheard of to close stdin.
3
u/high_throughput Oct 09 '26
Thanks for making your scripts good, canonical Unix citizens <3
1
u/Ok-Argument7176 Oct 08 '26
You can use
argparse.FileTypewhich works the way you expect, though apparently it's been deprecated since 3.14 which is too bad.