[issue32158] Suppress (and other contextlib context managers) should work as decorators (where appropriate)

Jason R. Coombs report at bugs.python.org
Fri Feb 9 12:39:42 EST 2018


Jason R. Coombs <jaraco at jaraco.com> added the comment:

In [this question](https://stackoverflow.com/a/48710609/70170), I encounter another case where a decorator would be useful. Without the decorator:

def is_docker():
	path = '/proc/self/cgroup'
	return (
		os.path.exists('/.dockerenv')
		or os.path.isfile(path)
		and any('docker' in line for line in open(path))
	)

With the decorator:

@suppress(FileNotFoundError)
def is_docker():
	return (
		os.path.exists('/.dockerenv')
		or any('docker' in line for line in open('/proc/self/cgroup'))
	)

The decorator enables several improvements:

- The boolean expression is now two expressions joined by 'or', which is semantically easier to parse and thus less prone to error than the three joined by and/or.
- There's no longer a need to create a path variable and reference it twice, allowing the value to appear inline where it's most relevant.
- The code is one line shorter.
- The body of the function is two lines shorter.
- The key behaviors the function is seeking to achieve are prominently presented.

Acknowledged there are two caveats:

- It's unclear the exception really is only expected in the 'open' call.
- In the case where the exception is suppressed, the function will return None, which while resolving to boolean False, isn't False.

Those caveats could be addressed, but will sacrifice readability or conciseness.

I don't think this use-case warrants re-opening the ticket or revisiting the issue, but I wanted to share for consideration.

----------

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue32158>
_______________________________________


More information about the Python-bugs-list mailing list