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_version
argument and the--source-version
optionin CLI
F2FORMAT_LINESEP
– same as thelinesep
argument and the--linesep
option in CLIF2FORMAT_INDENTATION
– same as theindentation
argument and the--indentation
option in CLIF2FORMAT_PEP8
– same as thepep8
argument and the--no-pep8
option 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-version
argument and the--source-version
optionin CLI
F2FORMAT_LINESEP
– same as thelinesep
argument and the--linesep
option in CLIF2FORMAT_INDENTATION
– same as theindentation
argument and the--indentation
option in CLIF2FORMAT_PEP8
– same as thepep8
argument and the--no-pep8
option in CLI (logical negation)F2FORMAT_QUIET
– same as thequiet
argument and the--quiet
option 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--quiet
option in CLIF2FORMAT_CONCURRENCY
– same as the--concurrency
option in CLIF2FORMAT_DO_ARCHIVE
– same as the--no-archive
option in CLI (logical negation)F2FORMAT_ARCHIVE_PATH
– same as the--archive-path
option in CLIF2FORMAT_SOURCE_VERSION
– same as the--source-version
option in CLIF2FORMAT_LINESEP
– same as the--linesep
option in CLIF2FORMAT_INDENTATION
– same as the--indentation
option in CLIF2FORMAT_PEP8
– same as the--no-pep8
option 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.BaseContext
General 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
raw
should beTrue
only if thenode
is in the clause of another context, where the converted wrapper functions should be inserted.For the
Context
class off2format
module, 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._prefix
andself._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
node
has 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
node
has 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
node
has 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
node
has 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
node
is 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.Context
String (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._prefix
andself._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
node
parameter.
- _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
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
- Environment Variables
F2FORMAT_QUIET
– the value in environment variable
See also
- 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
See also
- 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
- 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_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
- 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_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
- Environment Variables
F2FORMAT_SOURCE_VERSION
– the value in environment variable
See also
- 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
- 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
See also
- 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
- 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
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¶
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.See also
- f2format.__f2format_concurrency__: Union[int, Literal['auto detect']]¶
Default value for the
--concurrency
option.See also
- f2format.__f2format_do_archive__: Literal['will do archive', 'will not do archive']¶
Default value for the
--no-archive
option.See also
- f2format.__f2format_linesep__: Literal['LF', 'CRLF', 'CR', 'auto detect']¶
Default value for the
--linesep
option.See also
- f2format.__f2format_pep8__: Literal['will conform to PEP 8', 'will not conform to PEP 8']¶
Default value for the
--no-pep8
option.See also