Package Reference

This package transforms python source code strings or ast.Module Nodes into a ‘minified’ representation of the same source code.

python_minifier.minify(source, filename=None, remove_annotations=True, remove_pass=True, remove_literal_statements=False, combine_imports=True, hoist_literals=True, rename_locals=True, preserve_locals=None, rename_globals=False, preserve_globals=None, remove_object_base=True, convert_posargs_to_args=True)

Minify a python module

The module is transformed according the the arguments. If all transformation arguments are False, no transformations are made to the AST, the returned string will parse into exactly the same module.

Using the default arguments only transformations that are always or almost always safe are enabled.

Parameters
  • source (str) – The python module source code

  • filename (str) – The original source filename if known

  • remove_annotations (bool) – If type annotations should be removed where possible

  • remove_pass (bool) – If Pass statements should be removed where possible

  • remove_literal_statements (bool) – If statements consisting of a single literal should be removed, including docstrings

  • combine_imports (bool) – Combine adjacent import statements where possible

  • hoist_literals (bool) – If str and byte literals may be hoisted to the module level where possible.

  • rename_locals (bool) – If local names may be shortened

  • preserve_locals (list[str]) – Locals names to leave unchanged when rename_locals is True

  • rename_globals (bool) – If global names may be shortened

  • preserve_globals (list[str]) – Global names to leave unchanged when rename_globals is True

  • remove_object_base (bool) – If object as a base class may be removed

Return type

str

python_minifier.awslambda(source, filename=None, entrypoint=None)

Minify a python module for use as an AWS Lambda function

This returns a string suitable for embedding in a cloudformation template. When minifying, all transformations are enabled.

Parameters
  • source (str) – The python module source code

  • filename (str) – The original source filename if known

  • entrypoint (str or NoneType) – The lambda entrypoint function

Return type

str

python_minifier.unparse(module)

Turn a module AST into python code

This returns an exact representation of the given module, such that it can be parsed back into the same AST.

Parameters

module – The module to turn into python code

Type

module: ast.Module

Return type

str

exception python_minifier.UnstableMinification(exception, source, minified)

Raised when a minified module differs from the original module in an unexpected way.

This is raised when the minifier generates source code that doesn’t parse back into the original module (after known transformations). This should never occur and is a bug.