corpy.util

Small utility functions.

corpy.util.head(collection, first_n=None)

Inspect collection, truncated if too long.

>>> head(list(range(1_000)))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

If first_n=None, an appropriate value is determined based on the type of the collection.

corpy.util.cmp(lhs, rhs, test='__eq__')

Wrap assert statement to automatically raise an informative error.

corpy.util.clean_env(*, blacklist: Optional[Iterable[str]] = None, whitelist: Optional[Iterable[str]] = None, strict: bool = True, restore_builtins: bool = True, modules: bool = False, callables: bool = False, upper: bool = False, dunder: bool = False, sunder: bool = True)

Run a block of code in a sanitized global environment.

A context manager which temporarily removes global variables from scope:

>>> foo = 42
>>> with clean_env():
...     foo
...
Traceback (most recent call last):
  ...
NameError: name 'foo' is not defined

The original environment is restored at the end of the block:

>>> foo
42

Also works as a decorator, which is like wrapping the entire function body with the context manager:

>>> @clean_env()
... def return_foo():
...     return foo
...
>>> return_foo()
Traceback (most recent call last):
  ...
NameError: name 'foo' is not defined

By default, clean_env tries to be clever and leave e.g. functions alone, as well as other objects which are likely to be “legitimate” globals. It also restores overwritten builtins.

This is useful e.g. for testing answers in student assignments, because it will ensure that functions which accidentally capture global variables instead of using arguments fail.

Parameters
  • blacklist – A list of global variable names to always remove, irrespective of the other options.

  • whitelist – A list of global variable names to always keep, irrespective of the other options.

  • strict – In non-strict mode, allow global variables in the current scope, i.e. only start pruning within function calls. NOTE: This is slower because it requires tracing the function calls. Also, when using clean_env as a function decorator, non-strict probably doesn’t make sense.

  • restore_builtins – Make sure that the conventional names for built-in objects point to those objects (beginners often use list or sorted as variable names).

  • modules – Prune variables which refer to modules.

  • callables – Prune variables which refer to callables.

  • upper – Prune variables with all-uppercase identifiers (underscores allowed), which are likely to be intentional global variables (constants and the like).

  • dunder – Prune variables whose name starts with a double underscore.

  • sunder – Prune variables whose name starts with a single underscore.