Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/pasta/base/fstring_utils.py: 69%
16 statements
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-07 06:12 +0000
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-07 06:12 +0000
1# coding=utf-8
2"""Helpers for working with fstrings (python3.6+)."""
3# Copyright 2021 Google LLC
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# https://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
17from __future__ import absolute_import
18from __future__ import division
19from __future__ import print_function
21import ast
23_FSTRING_VAL_PLACEHOLDER = '__pasta_fstring_val_{index}__'
26def get_formatted_values(joined_str):
27 """Get all FormattedValues from a JoinedStr, in order."""
28 return [v for v in joined_str.values if isinstance(v, ast.FormattedValue)]
31def placeholder(val_index):
32 """Get the placeholder token for a FormattedValue in an fstring."""
33 return _FSTRING_VAL_PLACEHOLDER.format(index=val_index)
36def perform_replacements(fstr, values):
37 """Replace placeholders in an fstring with subexpressions."""
38 for i, value in enumerate(values):
39 fstr = fstr.replace(_wrap(placeholder(i)), _wrap(value))
40 return fstr
43def _wrap(s):
44 return '{%s}' % s