New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
partial_format() #84023
Comments
In
I think it could be useful to have a similar method for the format minilanguage. I propose a partial_format() method. === WHY I think this is useful? === This way, you can create subtemplates from a main template. You could want to use the template for creating a bunch of strings, all of them with the same value for some placeholders, but different values for other ones. This way you have *not* to reuse the same main template and substitute every time the placeholders that does not change.
Some example: >>> "{} {}".partial_format(1)
'1 {}'
>>> "{x} {a}".partial_format(a="elephants")
'{x} elephants'
>>> "{:-f} and {:-f} nights".partial_format(1000)
'1000 and {:-f} nights' |
Do you have some concrete use case for this, or is this a speculative feature request? This will do what you want, although it uses some undocumented internals of the _string module. I've only tested it a little, and I've done especially little testing for the error conditions: from _string import formatter_parser, formatter_field_name_split
def partial_format(spec, *args, **kwargs):
idx = 0
auto_number = False
manual_number = False
result = []
for literal_text, field_name, format_spec, conversion in formatter_parser(spec):
result.append(literal_text)
found = False
if field_name is None:
# We're at the end of the input.
break
if not field_name:
# Auto-numbering fields.
if manual_number:
raise ValueError(
"cannot switch from manual field specification to automatic field numbering"
)
auto_number = True
try:
value = args[idx]
idx += 1
found = True
except IndexError:
pass
elif isinstance(field_name, int):
# Numbered fields.
if auto_number:
raise ValueError(
"cannot switch from automatic field number to manual field specification"
)
manual_number = True
try:
value = args[field_name]
found = True
except IndexError:
pass
else:
# Named fields.
try:
value = kwargs[field_name]
found = True
except KeyError:
pass
spec = f":{format_spec}" if format_spec else ""
conv = f"!{conversion}" if conversion else ""
if found:
s = f"{{{conv}{spec}}}"
result.append(s.format(value))
else:
result.append(f"{{{field_name}{conv}{spec}}}")
|
Yes, for EWA: Since it's a code generator, it uses templates a lot, and much times I feel the need for a partial substitution. In the end I solved with some ugly tricks. Furthermore, if the method exists in the stdlib for |
I suggest using the version I posted here and see if it meets your needs. It uses the str.format parser to break the string into pieces, so it should be accurate as far as that goes. |
What would "{} {}".partial_format({}) return? It is not possible to implement a "safe" variant of str.format(), because in difference to Template it can call arbitrary code and allows easily to produce arbitrary large strings. Template is more appropriate if the template came from untrusted source or if it is composed by inexperienced user. |
If you read the documentation of But Python, for example, does not implement private class attributes. Because Python is for adult and consciousness people, no? |
@eric V. Smith: that you for your effort, but I'll never use an API marked as private, that is furthermore undocumented. |
Well, I'm the one who made them private, I can make them public if they're useful. But I won't do that if you're not willing to look at it. |
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
bugs.python.org fields:
The text was updated successfully, but these errors were encountered: