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
- 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 thesource_versionargument and the--source-versionoptionin CLI
F2FORMAT_LINESEP– same as thelinesepargument and the--linesepoption in CLIF2FORMAT_INDENTATION– same as theindentationargument and the--indentationoption in CLIF2FORMAT_PEP8– same as thepep8argument and the--no-pep8option in CLI (logical negation)
- Returns
converted source code
- Return type
- 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
- 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 thesource-versionargument and the--source-versionoptionin CLI
F2FORMAT_LINESEP– same as thelinesepargument and the--linesepoption in CLIF2FORMAT_INDENTATION– same as theindentationargument and the--indentationoption in CLIF2FORMAT_PEP8– same as thepep8argument and the--no-pep8option in CLI (logical negation)F2FORMAT_QUIET– same as thequietargument and the--quietoption in CLI
- Return type
- f2format.main(argv=None)[source]¶
Entry point for f2format.
- Parameters
argv (Optional[List[str]]) – CLI arguments
- Environment Variables
F2FORMAT_QUIET– same as the--quietoption in CLIF2FORMAT_CONCURRENCY– same as the--concurrencyoption in CLIF2FORMAT_DO_ARCHIVE– same as the--no-archiveoption in CLI (logical negation)F2FORMAT_ARCHIVE_PATH– same as the--archive-pathoption in CLIF2FORMAT_SOURCE_VERSION– same as the--source-versionoption in CLIF2FORMAT_LINESEP– same as the--linesepoption in CLIF2FORMAT_INDENTATION– same as the--indentationoption in CLIF2FORMAT_PEP8– same as the--no-pep8option in CLI (logical negation)
- Return type
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:
Conversion Contexts¶
- class f2format.Context(node, config, *, indent_level=0, raw=False)[source]¶
Bases:
bpc_utils.context.BaseContextGeneral conversion context.
- Parameters
node (parso.tree.NodeOrLeaf) – parso AST
config (Config) – conversion configurations
indent_level (int) –
raw (bool) –
- Keyword Arguments
raw (bool) – raw processing flag
- Return type
Important
rawshould beTrueonly if thenodeis in the clause of another context, where the converted wrapper functions should be inserted.For the
Contextclass off2formatmodule, it will process nodes with following methods:-
Context._process_string_context()
Initialize BaseContext.
- Parameters
node (
NodeOrLeaf) – parso ASTconfig (
Config) – conversion configurationsindent_level (
int) – current indentation levelraw (
bool) – raw processing flag
- Return type
- _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._prefixandself._suffix.- Return type
- _process_fstring(node)[source]¶
Process formatted strings (
f_string).- Parameters
node (parso.python.tree.PythonNode) – formatted strings node
- Return type
- _process_strings(node)[source]¶
Process concatenable strings (
stringliteral).- Parameters
node (parso.python.tree.PythonNode) – concatentable strings node
- Return type
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
- 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
nodehas debug formatted string literals- Return type
- classmethod has_expr(node)[source]¶
Check if node has formatted string literals.
- Parameters
node (parso.tree.NodeOrLeaf) – parso AST
- Returns
if
nodehas formatted string literals- Return type
- classmethod has_f2format(node)¶
Check if node has formatted string literals.
- Parameters
node (parso.tree.NodeOrLeaf) – parso AST
- Returns
if
nodehas formatted string literals- Return type
- classmethod has_fstring(node)[source]¶
Check if node has actual formatted string literals.
- Parameters
node (parso.tree.NodeOrLeaf) – parso AST
- Returns
- if
nodehas actual formatted string literals (with expressions in the literals)
- if
- Return type
- 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
nodeis debug formatted string literals- Return type
- _abc_impl = <_abc_data object>¶
- class f2format.StringContext(node, config, *, has_fstring=None, indent_level=0, raw=False)[source]¶
Bases:
f2format.ContextString (f-string) conversion context.
This class is mainly used for converting formatted string literals.
- Parameters
node (parso.python.tree.PythonNode) – parso AST
config (Config) – conversion configurations
has_fstring (Optional[bool]) –
indent_level (int) –
raw (bool) –
- Keyword Arguments
Initialize BaseContext.
- Parameters
node (
NodeOrLeaf) – parso ASTconfig (
Config) – conversion configurationsindent_level (
int) – current indentation levelraw (
bool) – raw processing flaghas_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._prefixandself._suffix.- Return type
- _process_fstring(node)[source]¶
Process formatted strings (
f_string).- Parameters
node (parso.python.tree.PythonNode) – formatted strings node
- Return type
- _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
- _process_fstring_start(node)[source]¶
Process formatted string literal starting node (
stringprefix).- Parameters
node (parso.python.tree.FStringStart) – formatted literal starting node
- Return type
- _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
- _process_string(node)[source]¶
Process string node (
stringliteral).- Parameters
node (parso.python.tree.PythonNode) – string node
- Return type
- _abc_impl = <_abc_data object>¶
- _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.
- _prefix_or_suffix: bool¶
Flag to indicate whether buffer is now
self._prefix.
- _root: Final[parso.tree.NodeOrLeaf]¶
Root node given by the
nodeparameter.
- _uuid_gen: Final[UUID4Generator]¶
UUID generator.
- 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
quietoption.- Parameters
explicit (Optional[bool]) – the value explicitly specified by user,
Noneif not specified- Returns
the value for the
quietoption- Return type
- Environment Variables
F2FORMAT_QUIET– the value in environment variable
See also
- f2format._get_concurrency_option(explicit=None)[source]¶
Get the value for the
concurrencyoption.- Parameters
explicit (Optional[int]) – the value explicitly specified by user,
Noneif not specified- Returns
the value for the
concurrencyoption;Nonemeans auto detection at runtime- Return type
Optional[int]
- Environment Variables
F2FORMAT_CONCURRENCY– the value in environment variable
See also
- f2format._get_do_archive_option(explicit=None)[source]¶
Get the value for the
do_archiveoption.- Parameters
explicit (Optional[bool]) – the value explicitly specified by user,
Noneif not specified- Returns
the value for the
do_archiveoption- Return type
- Environment Variables
F2FORMAT_DO_ARCHIVE– the value in environment variable
See also
- f2format._get_archive_path_option(explicit=None)[source]¶
Get the value for the
archive_pathoption.- Parameters
explicit (Optional[str]) – the value explicitly specified by user,
Noneif not specified- Returns
the value for the
archive_pathoption- Return type
- Environment Variables
F2FORMAT_ARCHIVE_PATH– the value in environment variable
See also
- f2format._get_source_version_option(explicit=None)[source]¶
Get the value for the
source_versionoption.- Parameters
explicit (Optional[str]) – the value explicitly specified by user,
Noneif not specified- Returns
the value for the
source_versionoption- Return type
- Environment Variables
F2FORMAT_SOURCE_VERSION– the value in environment variable
See also
- f2format._get_linesep_option(explicit=None)[source]¶
Get the value for the
linesepoption.- Parameters
explicit (Optional[str]) – the value explicitly specified by user,
Noneif not specified- Returns
the value for the
linesepoption;Nonemeans auto detection at runtime- Return type
Optional[Literal[‘\n’, ‘\r\n’, ‘\r’]]
- Environment Variables
F2FORMAT_LINESEP– the value in environment variable
See also
- f2format._get_indentation_option(explicit=None)[source]¶
Get the value for the
indentationoption.- Parameters
explicit (Optional[Union[str, int]]) – the value explicitly specified by user,
Noneif not specified- Returns
the value for the
indentationoption;Nonemeans auto detection at runtime- Return type
Optional[str]
- Environment Variables
F2FORMAT_INDENTATION– the value in environment variable
See also
- f2format._get_pep8_option(explicit=None)[source]¶
Get the value for the
pep8option.- Parameters
explicit (Optional[bool]) – the value explicitly specified by user,
Noneif not specified- Returns
the value for the
pep8option- Return type
- Environment Variables
F2FORMAT_PEP8– the value in environment variable
See also
The following variables are used for fallback default values of options.
- f2format._default_quiet = False¶
Default value for the
quietoption.
- f2format._default_concurrency = None¶
Default value for the
concurrencyoption.
- f2format._default_do_archive = True¶
Default value for the
do_archiveoption.
- f2format._default_archive_path = 'archive'¶
Default value for the
archive_pathoption.
- f2format._default_source_version = '3.10'¶
Default value for the
source_versionoption.
- f2format._default_linesep = None¶
Default value for the
linesepoption.
- f2format._default_indentation = None¶
Default value for the
indentationoption.
- f2format._default_pep8 = True¶
Default value for the
pep8option.
Important
For _default_concurrency, _default_linesep and _default_indentation,
None means auto detection during runtime.
CLI Utilities¶
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
--quietoption.See also
- f2format.__f2format_concurrency__: Union[int, Literal['auto detect']]¶
Default value for the
--concurrencyoption.See also
- f2format.__f2format_do_archive__: Literal['will do archive', 'will not do archive']¶
Default value for the
--no-archiveoption.See also
- f2format.__f2format_linesep__: Literal['LF', 'CRLF', 'CR', 'auto detect']¶
Default value for the
--linesepoption.See also
- f2format.__f2format_pep8__: Literal['will conform to PEP 8', 'will not conform to PEP 8']¶
Default value for the
--no-pep8option.See also