Skip to main content

Checks for hasattr, which is considered harmful in Plone projects

Project description

https://github.com/gforcada/flake8-plone-hasattr/actions/workflows/testing.yml/badge.svg?branch=master https://coveralls.io/repos/gforcada/flake8-plone-hasattr/badge.svg?branch=master

Flake8 Plone hasattr plugin

Python standard hasattr is considered harmful (within Plone projects).

The (hidden) problem with hasattr is that it swallows exceptions, which in your normal business logic you really don’t want to.

Specially in Plone context that could mean swallowing a database error, or a permission exception, etc.

Take, for instance, the following code:

>>> class Foo(object):
...     @property
...     def my_attr(self):
...         raise ValueError('nope, nope, nope')
...
>>> bar = Foo()
>>> bar.my_attr
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in my_attr
ValueError: nope, nope, nope
>>> hasattr(Foo, 'my_attr')
True
>>> hasattr(bar, 'my_attr')
False

One should rather do:

>>> getattr(bar, 'my_attr', None)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in my_attr
ValueError: nope, nope, nope

Or in case you want to handle an exception:

>>> try:
...     value = getattr(bar, 'my_attr', None)
... exception ValueError:
...     value = None

This plugin is based on a python checker that was in plone.recipe.codeanalysis.

Install

Install with pip:

$ pip install flake8-plone-hasattr

Requirements

  • Python 3.8, 3.9, 3.10, 3.11 and pypy3

  • flake8

License

GPL 2.0

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

flake8_plone_hasattr-1.1.1.tar.gz (13.3 kB view hashes)

Uploaded Source

Built Distribution

flake8_plone_hasattr-1.1.1-py3-none-any.whl (16.9 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page