Repository navigation
Closed
Labels
3.7 (EOL)end of life3.8 (EOL)end of lifestdlibStandard Library Python modules in the Lib/ directorytype-featureA feature request or enhancement
Description
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
assignee = 'https://github.com/ncoghlan'
closed_at = <Date 2017-11-23.00:27:28.912>
created_at = <Date 2010-10-08.11:13:44.343>
labels = ['3.7', '3.8', 'type-feature', 'library']
title = 'Add a "no-op" (null) context manager to contextlib'
updated_at = <Date 2017-11-23.00:27:28.910>
user = 'https://github.com/hniksic'bugs.python.org fields:
activity = <Date 2017-11-23.00:27:28.910>
actor = 'ncoghlan'
assignee = 'ncoghlan'
closed = True
closed_date = <Date 2017-11-23.00:27:28.912>
closer = 'ncoghlan'
components = ['Library (Lib)']
creation = <Date 2010-10-08.11:13:44.343>
creator = 'hniksic'
dependencies = []
files = ['19158', '19176']
hgrepos = []
issue_num = 10049
keywords = ['patch']
message_count = 43.0
messages = ['118181', '118183', '118184', '118185', '118186', '118187', '118189', '118190', '118193', '118194', '118195', '118196', '118200', '118274', '118406', '118409', '118448', '118450', '118453', '118599', '118616', '118626', '119514', '152909', '153046', '153049', '175656', '175662', '281177', '281180', '281195', '281200', '281215', '281234', '281264', '281556', '305951', '305952', '306001', '306002', '306266', '306770', '306771']
nosy_count = 18.0
nosy_names = ['georg.brandl', 'rhettinger', 'blais', 'ncoghlan', 'pitrou', 'vstinner', 'giampaolo.rodola', 'hniksic', 'eric.araujo', 'r.david.murray', 'michael.foord', 'daniel.urban', 'Albert.Zeyer', 'piotr.dobrogost', 'Alexander.Jones', 'DLitz', 'Martin Blais', 'jbakker']
pr_nums = ['4464']
priority = 'normal'
resolution = 'fixed'
stage = 'resolved'
status = 'closed'
superseder = None
type = 'enhancement'
url = 'https://bugs.python.org/issue10049'
versions = ['Python 3.7', 'Python 3.8']Metadata
Metadata
Assignees
Labels
3.7 (EOL)end of life3.8 (EOL)end of lifestdlibStandard Library Python modules in the Lib/ directorytype-featureA feature request or enhancement
Activity
hniksic commentedon Oct 8, 2010
I find that I frequently need the "null" (no-op) context manager. For example, in code such as:
Since there is no easy expression to create a null context manager, we must resort to workarounds, such as:
(with the usual options of moving the duplicated code to a function—but still.)
Or by creating ad-hoc null context managers with the help of contextlib.contextmanager:
Adding a "null" context manager would be both practical and elegant. I have attached a patch for contextlib.py
[-]Add the null context manager to contextlib[/-][+]Add a "no-op" (null) context manager to contextlib[/+]voidspace commentedon Oct 8, 2010
+1
Looks like a reasonable use case.
voidspace commentedon Oct 8, 2010
Patch is missing tests and documentation.
vstinner commentedon Oct 8, 2010
About your patch:
merwok commentedon Oct 8, 2010
I also find the Null/_null/null affair confusing.
pitrou commentedon Oct 8, 2010
Do we really need to add this to the stdlib?
Previous proposals to add an "identity function" or "no-op function" have always be refused. This one seems even less useful.
hniksic commentedon Oct 8, 2010
Thank you for your comments.
@michael: I will of course write tests and documentation if there is indication that the feature will be accepted for stdlib.
@antoine: it is true that a null context manager can be easily defined, but it does requires a separate generator definition, often repeated in different modules. This is markedly less elegant than just using contextlib.null() in an expression.
I'm not acquainted with the history of identity function requests, but note that the identity function can be defined as an expression, using simply lambda x: x. The equivalent expression that evaluates to a null context manager is markedly more convoluted, as shown in my report.
@Éric: The Null/_null/null distinction is an optimization that avoids creating new objects for something that is effectively a singleton. It would be perfectly reasonable to define contextlib.null as Antoine did, but, this being stdlib, I wanted the implementation to be as efficient as (reasonably) possible.
pitrou commentedon Oct 8, 2010
But you can use mymodule.null() where mymodule is a module gathering
common constructs of yours.
ncoghlan commentedon Oct 8, 2010
The difference here is the one pointed out in the original post: for a function, you usually only care about having a value, so if you don't want to call it, you can just swap in a None value instead. If you need an actual callable, then "lambda:None" fits the bill.
The with statement isn't quite so forgiving. You need a genuine context manager in order to preserve the correct structure in the calling code. It isn't intuitively obvious how to do that easily. While not every 3-line function needs to be in the standard library, sometimes they're worth including to aid discoverability as much as anything else.
However, I don't see the point in making it a singleton and the name should include the word "context" so it doesn't becoming ambiguous when referenced without the module name (there's a reason we went with contextlib.contextmanager over contextlib.manager).
Something like:
hniksic commentedon Oct 8, 2010
That is what we are using now, but I think a contextlib.null() would be useful to others, i.e. that its use is a useful idiom to adopt. Specifically I would like to discourage the "duplicated code" idiom from the report, which I've seen all too often.
The "closing" constructor is also trivial to define, but it's there for convenience and to promote the use of with statement over try/finally boilerplate. The same goes here: you don't miss the null context manager when you don't have it; you invent other solutions. But when it's already available, it's an elegant pattern. In my experience, if they have to define it to get it, most people won't bother with the pattern and will retain less elegant solutions.
ncoghlan commentedon Oct 8, 2010
Actually, the singleton idea isn't a bad one, but I'd go one step further and skip the factory function as well. So change that to be:
(with the example in the docstring adjusted accordingly)
ncoghlan commentedon Oct 8, 2010
If you can supply a full patch before the end of the month, we should be able to get this in for 3.2beta1 (currently scheduled for 31 October)
25 remaining items
ncoghlan commentedon Nov 20, 2016
Unfortunately, the redundancy doesn't buy enough to justify the permanent documentation and style guide cost of providing two ways to do exactly the same thing.
ncoghlan commentedon Nov 23, 2016
It turns out that there's a variant on the "null context manager" idea that may *not* be redundant with ExitStack(), and hence could potentially counter the current rationale for not adding one.
Specifically, it relates to context managers like click.progressbar() that are designed to be used with an "as" clause:
At the moment, making that optional is a bit messy, since you need to do something like:
or:
or:
The problem is that there's no easy way to say "return *this* value from __enter__, but otherwise don't do anything special".
With a suitably defined NullContext, that last approach could instead look more like:
albertz commentedon Nov 9, 2017
Note that this indeed seems confusing. I just found this thread by search for a null context manager. Because I found that in TensorFlow they introduced _NullContextmanager in their code and I wondered that this is not provided by the Python stdlib.
hniksic commentedon Nov 9, 2017
For what it's worth, we are still using our own null context manager function in critical code. We tend to avoid contextlib.ExitStack() for two reasons:
it is not immediately clear from looking at the code what ExitStack() means. (Unlike the "contextmanager" decorator, ExitStack is unfamiliar to most developers.)
ExitStack's __init__ and __exit__ incur a non-negligible overhead compared to a true do-nothing context manager.
It doesn't surprise me that projects like Tensor Flow introduce their own versions of this decorator. Having said that, I can also understand why it wasn't added. It is certainly possible to live without it, and ExitStack() is a more than acceptable replacement for casual use.
ncoghlan commentedon Nov 10, 2017
Reopening this based on several years of additional experience with context managers since I wrote https://bugs.python.org/issue10049#msg119514 when originally closing it.
The version I'm now interested in adding is the one from https://bugs.python.org/issue10049#msg281556 - rather than being completely without behaviour, the null context manager should accept the value to be returned from the call to __enter__ as an optional constructor parameter (defaulting to None). That allows even context managers that return a value from __enter__ to be made optional in a relatively obvious way that doesn't involve fundamentally rearranging the code.
I think the overhead argument against the use of ExitStack() for this purpose also has merit (so I'd be curious to see relative performance numbers collected with perf), but it's not my main motive for changing my mind.
[-]Add a "no-op" (null) context manager to contextlib (Rejected: use contextlib.ExitStack())[/-][+]Add a "no-op" (null) context manager to contextlib[/+]ncoghlan commentedon Nov 10, 2017
Reverting to "Needs patch", as the currently attached patch is for the "No behaviour" variant that always returns None from __enter__().
(hniksic, would you still be willing to sign the Python CLA? If so, then your patch could be used as the basis for an updated implementation. Otherwise I'd advise anyone working on this to start from scratch)
hniksic commentedon Nov 15, 2017
I am of course willing to sign the CLA (please send further instructions via email), although I don't know how useful my original patch is, given that it caches the null context manager.
ncoghlan commentedon Nov 23, 2017
New changeset 0784a2e by Nick Coghlan (Jesse-Bakker) in branch 'master':
bpo-10049: Add a "no-op" (null) context manager to contextlib (GH-4464)
0784a2e
ncoghlan commentedon Nov 23, 2017
Thanks to Jesse Bakker for the PR implementing this for 3.7!