rspec/rules/S2275/python/rule.adoc

71 lines
2.5 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
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
2020-06-30 12:48:07 +02:00
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
2020-06-30 12:48:07 +02:00
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'))
----
== Resources
2020-06-30 12:48:07 +02:00
* 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)
=== Message
* Fix this formatted string's syntax.
* Fix this formatted string's syntax; !z is not a valid conversion flag.
* Fix this string formatting; index 1 doesn't match any argument.
* Name unnamed conversion specifiers.
* Replace this formatting argument with a tuple.
* Replace this formatting argument with a mapping.
* Replace this value with a number as "%d" requires.
* Replace this value with an integer as "%X" requires.
* Replace this value with an integer as "*" requires.
* Add X missing argument(s).
* Remove X unexpected arguments.
* Provide a value for field "X".
* Replace this key; %-format accepts only string keys.
* Use only positional or only named field, don't mix them.
* Use only manual or only automatic field numbering, don't mix them.
'''
== Comments And Links
(visible only on this page)
include::../comments-and-links.adoc[]
endif::env-github,rspecator-view[]