Skip to main content

Library with convenience functions for generating code.

Project description

Code Writer

A Python 3 library with convenience functions for generating code in any language.

Based on the code generation backend in Stone that's used to generate code in many languages: C#, Java, Python, Ruby, Rust, Typescript, and more.

Why?

You know all of the pains with code generation (coding, build process, maintenance), but have decided you have no other choice. This library makes generating code a little bit more manageable.

Install

pip3 install code-writer

Usage

Basics

You'll need to import CodeWriter:

from code_writer import CodeWriter

Examples

You probably want to write the output of render() to a file, but for illustrative purposes we'll print them.

Hello, world.

cw = CodeWriter()
cw.emit('hello,')
with cw.indent():
    cw.emit('world.')
print(cw.render())

Output:

hello,
    world.

Python if statement

cw = CodeWriter()
cw.emit('if True:')
with cw.indent():
    cw.emit('print("hello, world.")')
print(cw.render())

Output:

if True:
    print("hello, world.")

Rust if statement

Use block() to create an indented block surrounding by curly braces.

cw = CodeWriter()
with cw.block(before='if true', delim=('{', '}')):
    cw.emit('println!("hello, world.");')
print(cw.render())

Output:

if true {
    println!("hello, world.");
}

You can also set a default delimiter:

cw = CodeWriter(default_delim=('{', '}'))

Tabs

cw = CodeWriter(use_tabs=True)

Indent two spaces

cw = CodeWriter(default_dent=2)

Generate lists

cw = CodeWriter()
cw.emit_list([], ('[', ']'), before='let li1 = ', after=';')
cw.emit_list(['1'], ('[', ']'), before='let li2 = ', after=';')
cw.emit_list(['1', '2', '3'], ('[', ']'), before='let li3 = ', after=';')
cw.emit_list(['1', '2', '3'], ('[', ']'), before='let li4 = ', after=';', compact=True)
print(cw.render())

Output:

let li1 = [];
let li2 = [1];
let li3 = [
    1,
    2,
    3,
];
let li4 = [1,
           2,
           3];

Generate wrapped text

This is useful for documentation.

# Artificially set col width low to show wrapped text
cw = CodeWriter(default_width=25)
cw.emit('/**')
cw.emit_wrapped_text(
    '@param param1 an explanation of what this argument does.',
    prefix=' * ',
    indent_after_first=True,
)
cw.emit('*/')
print(cw.render())

Output:

/**
 * @param param1 an
 *     explanation of
 *     what this argument
 *     does.
*/

Emit a preamble or header

preamble = """\
This
is
a
preamble.
"""
cw = CodeWriter()
cw.emit_raw(preamble)
print(cw.render())

Output:

This
is
a
preamble.

Trim trailing newlines

Sometimes you'll want a newline after every iteration of logic, but not for the last iteration.

cw = CodeWriter()
with cw.block(before='if true', delim=('{', '}')):
    for i in range(3):
        cw.emit('println!("{}");'.format(i))
        cw.emit()
print(cw.render())

Output:

if true {
    println!("0");

    println!("1");

    println!("2");

}

The gap after the last println!() is undesirable. To fix, do this:

cw = CodeWriter()
with cw.block(before='if true', delim=('{', '}')):
    for i in range(3):
        cw.emit('println!("{}");'.format(i))
        cw.emit()
    cw.trim_last_line_if_empty()
print(cw.render())

Output:

if true {
    println!("0");

    println!("1");

    println!("2");
}

Naming conventions

Depending on your target language, you may need to output names that are PascalCase, camelCase, underscore_delimited, or dash-delimited.

from code_writer import fmt_camel, fmt_dashes, fmt_pascal, fmt_underscores
# The input name can be a mix of formatting. These helpers will aggressively
# split the word and re-assemble as desired.
text = 'a-B-HiHo-merryOh_yes_no_XYZ'
assert fmt_camel(text) == 'aBHiHoMerryOhYesNoXyz'
assert fmt_dashes(text) == 'a-b-hi-ho-merry-oh-yes-no-xyz'
assert fmt_pascal(text) == 'ABHiHoMerryOhYesNoXyz'
assert fmt_underscores(text) == 'a_b_hi_ho_merry_oh_yes_no_xyz'

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

code-writer-1.0.1.tar.gz (7.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

code_writer-1.0.1-py3-none-any.whl (6.9 kB view details)

Uploaded Python 3

File details

Details for the file code-writer-1.0.1.tar.gz.

File metadata

  • Download URL: code-writer-1.0.1.tar.gz
  • Upload date:
  • Size: 7.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.13.0 pkginfo/1.5.0.1 requests/2.18.4 setuptools/40.7.1 requests-toolbelt/0.9.1 tqdm/4.31.1 CPython/3.6.7

File hashes

Hashes for code-writer-1.0.1.tar.gz
Algorithm Hash digest
SHA256 1e68433056c4569e12bed41ee539441c5b4af9ed76a601250f8e261a1a5fc9fe
MD5 40dc30b07ef37cfb13cbeb20e41df0ff
BLAKE2b-256 b7dac9e48608319fe85f7ea93bb1d41c94a71fe6c656acfb818313dfe6429d7a

See more details on using hashes here.

File details

Details for the file code_writer-1.0.1-py3-none-any.whl.

File metadata

  • Download URL: code_writer-1.0.1-py3-none-any.whl
  • Upload date:
  • Size: 6.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.13.0 pkginfo/1.5.0.1 requests/2.18.4 setuptools/40.7.1 requests-toolbelt/0.9.1 tqdm/4.31.1 CPython/3.6.7

File hashes

Hashes for code_writer-1.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 c59449327823992e86b8d16c5c4dbdb532500e0a738956fe5d7451bca137656a
MD5 a14dd8dc68ea751a6d65a8e1ce36f3f6
BLAKE2b-256 7d60721b39768f3a2be0043994b0baa6f1fa2c74c37dbfd73142716098a77bc0

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page