Python `contextvars` don't persist across cells in notebook
See original GitHub issuePython 3.7 added a new contextvars
package to “manage, store, and access context-local state”.
However, if I set a ContextVar
in one cell and then try to get it in another, it isn’t persisted:
This may be an antipattern (not sure if there is a good use case to set a variable across many cells) and I worked around it by setting default
, as recommended. However it is surprising and is different than how ipython
works.
Issue Analytics
- State:
- Created 5 years ago
- Reactions:5
- Comments:10 (7 by maintainers)
Top Results From Across the Web
[Example code]-Context variables in Python
Suppose that I have a function in my Python application that define some kind of context - a user_id for example. This function...
Read more >Spatial mapping of cell types across the mouse brain (2/3)
This notebook demonstrates how to use the cell2location model for mapping a single cell reference cell types onto a spatial transcriptomic dataset.
Read more >Python Documentation contents — Python 3.11.1 documentation
What can be pickled and unpickled? Pickling Class Instances · Persistence of External Objects · Dispatch Tables · Handling Stateful Objects · Custom...
Read more >contextvars — Context Variables - Python 3.7.3 Documentation
The ContextVar class is used to declare and work with Context Variables. ... If there is no value for the variable in the...
Read more >Changelog — DataRobot Python Client 3.0.2 documentation
... in IPython notebooks, where API credentials did not persist across cells ... The DataRobot Python Client is no longer published under the...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
This produces surprising results when changing the
decimal
precision (or other aspects of the decimal context) in notebooks, sincedecimal
now uses a PEP 567 context variable for the decimal context.Related: https://github.com/ipython/ipykernel/issues/494, https://github.com/jupyter/notebook/issues/5260
I believe tornado on py3 uses the asyncio loop by default, and if you’re on py 3.7 then asyncio will automatically use different contexts for different tasks. And probably each cell execution counts as a different task as far as tornado/aio is concerned.
Sounds like the kernel should be explicitly holding a
Context
object and reusing it for each cell execution, instead of letting tornado/aio set theContext
implicitly.