rspec/rules/S5755/python/rule.adoc

74 lines
1.7 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
2021-04-28 16:49:39 +02:00
Accessing a non-existing member on an object will raise in most case an ``++AttributeError++`` exception.
This rule raises an issue when a non-existing member is accessed on a class instance and nothing indicates that this was expected.
=== Noncompliant code example
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,python]
2021-04-28 16:49:39 +02:00
----
def access_attribute():
x = 42
return x.isnumeric() # Noncompliant
----
=== Compliant solution
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,python]
2021-04-28 16:49:39 +02:00
----
def access_attribute():
x = "42"
return x.isnumeric()
----
=== Exceptions
2021-04-28 16:49:39 +02:00
No issue will be raised:
* in ``++try ... except++`` blocks when ``++AttributeError++`` is caught.
* in ``++if hasattr(...)++`` blocks.
* when the accessed object has methods ``++__getattribute__++`` or ``++__getattr__++``. These methods will override the default attribute access behavior.
* when a class or its parent classes use ``++setattr++``. This can be used to add dynamically members to the class, even if it is not recommended.
You can also disable any issue for a given class by adding it to this rule's ignoredClassesForMemberValidation property.
== Resources
2021-04-28 16:49:39 +02:00
* https://youtu.be/NiSqG6s8skA[The Magic of Attribute Access - by Petr Viktorin - EuroPython Conference 2014]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Fix this access to a non-existing member "XXX"
=== Parameters
.ignoredClassesForMemberValidation
****
Comma-separated list of classes whose members will not be validated.
****
=== Highlighting
Primary: the member access
Secondary: the code giving us a clue on the type of the object whose member we try to access. Example: the assignment, the "if x is None" check...
endif::env-github,rspecator-view[]