Created
May 11, 2021 14:07
-
-
Save garfieldnate/6981f2ca515bbf907e2c609d3505378d to your computer and use it in GitHub Desktop.
check that your handling of global variables in a Jupyter notebook is clean
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import inspect | |
from IPython.display import display, HTML | |
def html(s): | |
return display(HTML(s)) | |
def ok(message="OK"): | |
html(f"<div class=\"alert alert-block alert-success\">{message}</div>") | |
def _acceptable_global(name, value): | |
"""Returns True if a global variable with name/value can be safely ignored""" | |
return ( | |
# stuff that's normal to share everywhere | |
inspect.isroutine(value) or | |
inspect.isclass(value) or | |
inspect.ismodule(value) or | |
# leading underscore marks private variables | |
name.startswith('_') or | |
# all-caps names indicate constants | |
name.upper() == name or | |
# ignore IPython stuff | |
name in {'In', 'Out'} or | |
getattr(value, '__module__', '').startswith('IPython')) | |
def assert_globals_clean(): | |
"""Raises an assertion error if there are unmanaged global variables. | |
Variables that are considered 'managed' include those formatted with | |
ALL_CAPS (constants), _a_leading_underscore (recognized as a global but at | |
least indicated as private to the cell), classes and modules, automatic | |
imports from IPython, and functions generally.""" | |
unmanaged_globals = {k:type(v) for k, v in globals().items() if not _acceptable_global(k, v)} | |
if unmanaged_globals != {}: | |
raise AssertionError(f"Unmanaged globals found: {unmanaged_globals}") | |
ok("No unmanaged globals detected") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment