DEV Community

Discussion on: How would you rewrite this Python code?

Collapse
 
thinkslynk profile image
Stephen Dycus

I think the cleanest way is this:

if filename:
    with (open(filename, 'w') as file:
        do_something(file)
else:
    do_something(sys.stdout)
Collapse
 
cathodion profile image
Dustin King

Certainly works if do_something is just a function call. I meant it as a stand-in for a larger block of code. But maybe that block should actually be a function.

Collapse
 
blubberdiblub profile image
Niels Böhm

Yes, it should be a function. stdout/stderr/stdin are different from other streams in that they're managed outside (by the OS and Python, not by your app) whereas an open should be used with with in simple cases if possible.

You can start treating them the same when you start writing to / reading from them and stop when you stop doing that. All that can nicely be stuck away in a function. That also enables you to call the actual I/O part with a different file-like thing, say a StringIO instance when testing.