Hello,
I’m working with “Format String Syntax” specification, more specifically the grammar part:
So I’m talking about new-style formating (example: "{} some template with {data}".format(1, data=[1, 2, 3])
).
As I see the “field_name” (if present) starts with “arg_name”.
And “arg_name” can only be
- empty
- identifier
- digits
So I don’t expect any other “arg_names” values passed to str.format()
method to be valid.
Following the grammar and new-style formatting mechanics all named fields from template would be treated with “arg_names” option №2 from the list above (identifiers).
And I expected all “identifier” named fields are validated with str.isidintifier()
– any of them having False
for this expression would produce error similar to this:
In [30]: def f(**kwargs):
...: print(kwargs)
...:
In [31]: d = {None: 12, 12: 212121}
In [32]: f(**d)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[32], line 1
----> 1 f(**d)
TypeError: keywords must be strings
But I found out that this is not true. Here is an example:
In [29]: "{a-b} {-}".format(**{"-": "_-_", "a-b": "ABC"})
Out[29]: 'ABC _-_'
I wrote a template that is invalid (in terms of grammar above) and formatted it using kwargs mechanics –and it succeeded.
I think it’s related to **kwargs
mechanics in function mechanics which allows passing any dict having only string keys. This kwargs mechanics have no “isidentifier” constraint.
Seems like such “isidentifier” constraint is missing in str.format()
implementation.
Or there is an issue in documentation.
Can you please comment this situation?
I’m wondering is this a bug in implementation and could be fixed or it’s expected behavior with docs issue.
P.S. It really matters for library I’m working on.