minification.py - For minifying Python code

Module for minification functions.

pyminifier.minification.dedent(source, use_tabs=False)[source]

Minimizes indentation to save precious bytes. Optionally, use_tabs may be specified if you want to use tabulators ( ) instead of spaces.

Example:

def foo(bar):
    test = "This is a test"

Will become:

def foo(bar):
 test = "This is a test"
pyminifier.minification.fix_empty_methods(source)[source]

Appends ‘pass’ to empty methods/functions (i.e. where there was nothing but a docstring before we removed it =).

Example:

# Note: This triple-single-quote inside a triple-double-quote is also a
# pyminifier self-test
def myfunc():
    '''This is just a placeholder function.'''

Will become:

def myfunc(): pass
pyminifier.minification.join_multiline_pairs(text, pair='()')[source]

Finds and removes newlines in multiline matching pairs of characters in text.

By default it joins parens () but it will join any two characters given via the pair variable.

Note

Doesn’t remove extraneous whitespace that ends up between the pair. Use reduce_operators() for that.

Example:

test = (
    "This is inside a multi-line pair of parentheses"
)

Will become:

test = (            "This is inside a multi-line pair of parentheses"        )
pyminifier.minification.minify(tokens, options)[source]

Performs minification on tokens according to the values in options

pyminifier.minification.reduce_operators(source)[source]

Remove spaces between operators in source and returns the result.

Example:

def foo(foo, bar, blah):
    test = "This is a %s" % foo

Will become:

def foo(foo,bar,blah):
    test="This is a %s"%foo
pyminifier.minification.remove_blank_lines(source)[source]

Removes blank lines from source and returns the result.

Example:

test = "foo"

test2 = "bar"

Will become:

test = "foo"
test2 = "bar"
pyminifier.minification.remove_comments(tokens)[source]

Removes comments from tokens which is expected to be a list equivalent of tokenize.generate_tokens() (so we can update in-place).

Note

  • If the comment makes up the whole line, the newline will also be removed (so you don’t end up with lots of blank lines).
  • Preserves shebangs and encoding strings.
pyminifier.minification.remove_comments_and_docstrings(source)[source]

Returns source minus comments and docstrings.

Note

Uses Python’s built-in tokenize module to great effect.

Example:

def noop(): # This is a comment
    '''
    Does nothing.
    '''
    pass # Don't do anything

Will become:

def noop():
    pass
pyminifier.minification.remove_docstrings(tokens)[source]

Removes docstrings from tokens which is expected to be a list equivalent of tokenize.generate_tokens() (so we can update in-place).