rspec/rules/S2275/python/rule.adoc

51 lines
1.8 KiB
Plaintext
Raw Normal View History

2021-01-27 13:42:22 +01:00
Formatting strings, either with the ``++%++`` operator or ``++str.format++`` method, requires a valid string and arguments matching this string's replacement fields.
2020-06-30 12:48:07 +02:00
2021-02-02 15:02:10 +01:00
2020-06-30 12:48:07 +02:00
This rule raises an issue when formatting a string will raise an exception because the input string or arguments are invalid. Rule S3457 covers cases where no exception is raised and the resulting string is simply not formatted properly.
== Noncompliant Code Example
2022-02-04 17:28:24 +01:00
[source,python]
2020-06-30 12:48:07 +02:00
----
print('Error code %d' % '42') # Noncompliant. Replace this value with a number as %d requires.
print('User {1} is not allowed to perform this action'.format('Bob')) # Noncompliant. Replacement field numbering should start at 0.
print('User {0} has not been able to access {}'.format('Alice', 'MyFile')) # Noncompliant. Use only manual or only automatic field numbering, don't mix them.
print('User {a} has not been able to access {b}'.format(a='Alice')) # Noncompliant. Provide a value for field "b".
----
== Compliant Solution
2022-02-04 17:28:24 +01:00
[source,python]
2020-06-30 12:48:07 +02:00
----
print('Error code %d' % 42)
print('User {0} is not allowed to perform this action'.format('Bob'))
print('User {0} has not been able to access {1}'.format('Alice', 'MyFile'))
print('User {a} has not been able to access {b}'.format(a='Alice', b='MyFile'))
----
== See
* https://docs.python.org/3/library/string.html#format-string-syntax[Python documentation - Format String Syntax]
* https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting[Python documentation - printf-style String Formatting]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
include::message.adoc[]
'''
== Comments And Links
(visible only on this page)
include::../comments-and-links.adoc[]
endif::env-github,rspecator-view[]