API Reference

Public Interface

f2format.convert(code, filename=None, *, source_version=None, linesep=None, indentation=None, pep8=None)[source]

Convert the given Python source code string.

Parameters
  • code (Union[str, bytes]) – the source code to be converted

  • filename (Optional[str]) – an optional source file name to provide a context in case of error

  • source_version (Optional[str]) –

  • linesep (Optional[Literal[ , , ]]) –

  • indentation (Optional[Union[str, int]]) –

  • pep8 (Optional[bool]) –

Keyword Arguments

source_version (Optional[str]) – parse the code as this Python version (uses the latest version by default)

Environment Variables
  • F2FORMAT_SOURCE_VERSION – same as the source_version argument and the --source-version option

    in CLI

  • F2FORMAT_LINESEP – same as the linesep argument and the --linesep option in CLI

  • F2FORMAT_INDENTATION – same as the indentation argument and the --indentation option in CLI

  • F2FORMAT_PEP8 – same as the pep8 argument and the --no-pep8 option in CLI (logical negation)

Returns

converted source code

Return type

str

f2format.f2format(filename, *, source_version=None, linesep=None, indentation=None, pep8=None, quiet=None, dry_run=False)[source]

Convert the given Python source code file. The file will be overwritten.

Parameters
  • filename (str) – the file to convert

  • source_version (Optional[str]) –

  • linesep (Optional[Literal[ , , ]]) –

  • indentation (Optional[Union[str, int]]) –

  • pep8 (Optional[bool]) –

  • quiet (Optional[bool]) –

  • dry_run (bool) –

Keyword Arguments
  • source_version (Optional[str]) – parse the code as this Python version (uses the latest version by default)

  • linesep (Optional[str]) – line separator of code (LF, CRLF, CR) (auto detect by default)

  • indentation (Optional[Union[int, str]]) – code indentation style, specify an integer for the number of spaces, or 't'/'tab' for tabs (auto detect by default)

  • pep8 (Optional[bool]) – whether to make code insertion PEP 8 compliant

  • quiet (Optional[bool]) – whether to run in quiet mode

  • dry_run (bool) – if True, only print the name of the file to convert but do not perform any conversion

Environment Variables
  • F2FORMAT_SOURCE_VERSION – same as the source-version argument and the --source-version option

    in CLI

  • F2FORMAT_LINESEP – same as the linesep argument and the --linesep option in CLI

  • F2FORMAT_INDENTATION – same as the indentation argument and the --indentation option in CLI

  • F2FORMAT_PEP8 – same as the pep8 argument and the --no-pep8 option in CLI (logical negation)

  • F2FORMAT_QUIET – same as the quiet argument and the --quiet option in CLI

Return type

None

f2format.main(argv=None)[source]

Entry point for f2format.

Parameters

argv (Optional[List[str]]) – CLI arguments

Environment Variables
  • F2FORMAT_QUIET – same as the --quiet option in CLI

  • F2FORMAT_CONCURRENCY – same as the --concurrency option in CLI

  • F2FORMAT_DO_ARCHIVE – same as the --no-archive option in CLI (logical negation)

  • F2FORMAT_ARCHIVE_PATH – same as the --archive-path option in CLI

  • F2FORMAT_SOURCE_VERSION – same as the --source-version option in CLI

  • F2FORMAT_LINESEP – same as the --linesep option in CLI

  • F2FORMAT_INDENTATION – same as the --indentation option in CLI

  • F2FORMAT_PEP8 – same as the --no-pep8 option in CLI (logical negation)

Return type

int

Conversion Implementation

The main logic of the f2format conversion is to extract the expressions part from formatted string literals and rewrite the original f-string using str.format syntax.

For conversion algorithms and details, please refer to Algorithms.

Data Structures

During conversion, we utilised bpc_utils.Config to store and deliver the configurations over the conversion Context instances, which should be as following:

class f2format.Config[source]

Configuration object shared over the conversion process of a single source file.

indentation: str

Indentation sequence.

linesep: Literal['\n', '\r\n', '\r']

Line separator.

pep8: bool

PEP 8 compliant conversion flag.

filename: Optional[str]

An optional source file name to provide a context in case of error.

source_version: Optional[str]

Parse the code as this Python version (uses the latest version by default).

Conversion Contexts

class f2format.Context(node, config, *, indent_level=0, raw=False)[source]

Bases: bpc_utils.context.BaseContext

General conversion context.

Parameters
Keyword Arguments

raw (bool) – raw processing flag

Return type

None

Important

raw should be True only if the node is in the clause of another context, where the converted wrapper functions should be inserted.

For the Context class of f2format module, it will process nodes with following methods:

Initialize BaseContext.

Parameters
  • node (NodeOrLeaf) – parso AST

  • config (Config) – conversion configurations

  • indent_level (int) – current indentation level

  • raw (bool) – raw processing flag

Return type

None

_concat()[source]

Concatenate final string.

This method tries to concatenate final result based on the very location where starts to contain formatted string literals, i.e. between the converted code as self._prefix and self._suffix.

Return type

None

_process_fstring(node)[source]

Process formatted strings (f_string).

Parameters

node (parso.python.tree.PythonNode) – formatted strings node

Return type

None

_process_strings(node)[source]

Process concatenable strings (stringliteral).

Parameters

node (parso.python.tree.PythonNode) – concatentable strings node

Return type

None

As in Python, adjacent string literals can be concatenated in certain cases, as described in the documentation. Such concatenable strings may contain formatted string literals (f-string) within its scope.

Return type

None

Parameters

node (parso.python.tree.PythonNode) –

classmethod has_debug_fstring(node)[source]

Check if node has debug formatted string literals.

Parameters

node (parso.tree.NodeOrLeaf) – parso AST

Returns

if node has debug formatted string literals

Return type

bool

classmethod has_expr(node)[source]

Check if node has formatted string literals.

Parameters

node (parso.tree.NodeOrLeaf) – parso AST

Returns

if node has formatted string literals

Return type

bool

classmethod has_f2format(node)

Check if node has formatted string literals.

Parameters

node (parso.tree.NodeOrLeaf) – parso AST

Returns

if node has formatted string literals

Return type

bool

classmethod has_fstring(node)[source]

Check if node has actual formatted string literals.

Parameters

node (parso.tree.NodeOrLeaf) – parso AST

Returns

if node has actual formatted string literals

(with expressions in the literals)

Return type

bool

static is_debug_fstring(node)[source]

Check if node is debug formatted string literal expression (f_expression).

Parameters

node (parso.python.tree.PythonNode) – formatted literal expression node

Returns

if node is debug formatted string literals

Return type

bool

_abc_impl = <_abc_data object>
class f2format.StringContext(node, config, *, has_fstring=None, indent_level=0, raw=False)[source]

Bases: f2format.Context

String (f-string) conversion context.

This class is mainly used for converting formatted string literals.

Parameters
Keyword Arguments
  • has_fstring (bool) – flag if contains actual formatted string literals (with expressions)

  • indent_level (int) – current indentation level

  • raw (bool) – raw processing flag

Initialize BaseContext.

Parameters
  • node (NodeOrLeaf) – parso AST

  • config (Config) – conversion configurations

  • indent_level (int) – current indentation level

  • raw (bool) – raw processing flag

  • has_fstring (Optional[bool]) –

_concat()[source]

Concatenate final string.

This method tries to concatenate final result based on the very location where starts to contain formatted string literals, i.e. between the converted code as self._prefix and self._suffix.

Return type

None

_process_fstring(node)[source]

Process formatted strings (f_string).

Parameters

node (parso.python.tree.PythonNode) – formatted strings node

Return type

None

_process_fstring_expr(node)[source]

Process formatted string literal expression node (f_expression).

Parameters

node (parso.python.tree.PythonNode) – formatted literal expression node

Return type

None

_process_fstring_start(node)[source]

Process formatted string literal starting node (stringprefix).

Parameters

node (parso.python.tree.FStringStart) – formatted literal starting node

Return type

None

_process_fstring_string(node)[source]

Process formatted string literal string node (stringliteral).

Parameters

node (parso.python.tree.FStringString) – formatted string literal string node

Return type

None

_process_string(node)[source]

Process string node (stringliteral).

Parameters

node (parso.python.tree.PythonNode) – string node

Return type

None

_abc_impl = <_abc_data object>
_buffer: str

Final converted result.

_expr: List[str]

Expressions extracted from the formatted string literal.

Type

List[str]

_flag: bool

Flag if contains actual formatted string literals (with expressions).

Type

bool

_indent_level: Final[int]

Current indentation level.

_indentation: Final[str]

Indentation sequence.

_linesep: Final[Linesep]

Line seperator.

Type

Final[Linesep]

_node_before_expr: Optional[parso.tree.NodeOrLeaf]

Preceding node with the target expression, i.e. the insertion point.

_pep8: Final[bool]

PEP 8 compliant conversion flag.

_prefix: str

Code before insertion point.

_prefix_or_suffix: bool

Flag to indicate whether buffer is now self._prefix.

_root: Final[parso.tree.NodeOrLeaf]

Root node given by the node parameter.

_suffix: str

Code after insertion point.

_uuid_gen: Final[UUID4Generator]

UUID generator.

config: Final[Config]

Internal configurations.

property expr: List[str]

Expressions extracted from the formatted string literal.

Return type

List[str]

fstring_bracket: Final[ClassVar[re.Pattern]] = re.compile('([{}])', re.ASCII)

Pattern matches single brackets in the formatted string literal ({}).

Type

re.Pattern

fstring_start: Final[ClassVar[re.Pattern]] = re.compile('[fF]', re.ASCII)

Pattern matches the formatted string literal prefix (f).

Type

re.Pattern

Internal Auxiliaries

Options & Defaults

f2format.F2FORMAT_SOURCE_VERSIONS = ['3.6', '3.7', '3.8', '3.9', '3.10']

Get supported source versions.

Below are option getter utility functions. Option value precedence is:

explicit value (CLI/API arguments) > environment variable > default value
f2format._get_quiet_option(explicit=None)[source]

Get the value for the quiet option.

Parameters

explicit (Optional[bool]) – the value explicitly specified by user, None if not specified

Returns

the value for the quiet option

Return type

bool

Environment Variables

F2FORMAT_QUIET – the value in environment variable

See also

_default_quiet

f2format._get_concurrency_option(explicit=None)[source]

Get the value for the concurrency option.

Parameters

explicit (Optional[int]) – the value explicitly specified by user, None if not specified

Returns

the value for the concurrency option; None means auto detection at runtime

Return type

Optional[int]

Environment Variables

F2FORMAT_CONCURRENCY – the value in environment variable

f2format._get_do_archive_option(explicit=None)[source]

Get the value for the do_archive option.

Parameters

explicit (Optional[bool]) – the value explicitly specified by user, None if not specified

Returns

the value for the do_archive option

Return type

bool

Environment Variables

F2FORMAT_DO_ARCHIVE – the value in environment variable

f2format._get_archive_path_option(explicit=None)[source]

Get the value for the archive_path option.

Parameters

explicit (Optional[str]) – the value explicitly specified by user, None if not specified

Returns

the value for the archive_path option

Return type

str

Environment Variables

F2FORMAT_ARCHIVE_PATH – the value in environment variable

f2format._get_source_version_option(explicit=None)[source]

Get the value for the source_version option.

Parameters

explicit (Optional[str]) – the value explicitly specified by user, None if not specified

Returns

the value for the source_version option

Return type

str

Environment Variables

F2FORMAT_SOURCE_VERSION – the value in environment variable

f2format._get_linesep_option(explicit=None)[source]

Get the value for the linesep option.

Parameters

explicit (Optional[str]) – the value explicitly specified by user, None if not specified

Returns

the value for the linesep option; None means auto detection at runtime

Return type

Optional[Literal[‘\n’, ‘\r\n’, ‘\r’]]

Environment Variables

F2FORMAT_LINESEP – the value in environment variable

See also

_default_linesep

f2format._get_indentation_option(explicit=None)[source]

Get the value for the indentation option.

Parameters

explicit (Optional[Union[str, int]]) – the value explicitly specified by user, None if not specified

Returns

the value for the indentation option; None means auto detection at runtime

Return type

Optional[str]

Environment Variables

F2FORMAT_INDENTATION – the value in environment variable

f2format._get_pep8_option(explicit=None)[source]

Get the value for the pep8 option.

Parameters

explicit (Optional[bool]) – the value explicitly specified by user, None if not specified

Returns

the value for the pep8 option

Return type

bool

Environment Variables

F2FORMAT_PEP8 – the value in environment variable

See also

_default_pep8

The following variables are used for fallback default values of options.

f2format._default_quiet = False

Default value for the quiet option.

f2format._default_concurrency = None

Default value for the concurrency option.

f2format._default_do_archive = True

Default value for the do_archive option.

f2format._default_archive_path = 'archive'

Default value for the archive_path option.

f2format._default_source_version = '3.10'

Default value for the source_version option.

f2format._default_linesep = None

Default value for the linesep option.

f2format._default_indentation = None

Default value for the indentation option.

f2format._default_pep8 = True

Default value for the pep8 option.

Important

For _default_concurrency, _default_linesep and _default_indentation, None means auto detection during runtime.

CLI Utilities

f2format.get_parser()[source]

Generate CLI parser.

Returns

CLI parser for f2format

Return type

argparse.ArgumentParser

The following variables are used for help messages in the argument parser.

f2format.__cwd__: str

Current working directory returned by os.getcwd().

f2format.__f2format_quiet__: Literal['quiet mode', 'non-quiet mode']

Default value for the --quiet option.

f2format.__f2format_concurrency__: Union[int, Literal['auto detect']]

Default value for the --concurrency option.

f2format.__f2format_do_archive__: Literal['will do archive', 'will not do archive']

Default value for the --no-archive option.

f2format.__f2format_archive_path__: str

Default value for the --archive-path option.

f2format.__f2format_source_version__: str

Default value for the --source-version option.

f2format.__f2format_linesep__: Literal['LF', 'CRLF', 'CR', 'auto detect']

Default value for the --linesep option.

f2format.__f2format_indentation__: str

Default value for the --indentation option.

f2format.__f2format_pep8__: Literal['will conform to PEP 8', 'will not conform to PEP 8']

Default value for the --no-pep8 option.