Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add hasattr function #235

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions documentation/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -473,6 +473,19 @@ string data in all Python versions.
that returns the result of ``__unicode__()`` encoded with UTF-8.


Behavior changes
>>>>>>>>>>>>>>>>

Six also provides shims for changes in behavior.

.. function:: hasattr(obj, name)

In Python 2, hasattr() catches all exceptions, while on Python 3 it only
catches `~py3:AttributeError`. On Python 3, this function is an alias to
`~py3:hasattr`. On Python 2, it implements the (more sensible) Python 3
behaviour


unittest assertions
>>>>>>>>>>>>>>>>>>>

Expand Down
14 changes: 14 additions & 0 deletions six.py
Original file line number Diff line number Diff line change
Expand Up @@ -925,6 +925,20 @@ def python_2_unicode_compatible(klass):
return klass


if PY2:
def hasattr(obj, name):
"""Return whether the object has an attribute with the given name.

This is done by calling getattr(obj, name) and catching AttributeError."""
try:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think

        try:
            getattr(obj, attr_name)
        except AttributeError:
            return False
        return True

is a bit nicer

getattr(obj, name)
return True
except AttributeError:
return False
else:
hasattr = hasattr


# Complete the moves implementation.
# This code is at the end of this module to speed up module loading.
# Turn this module into a package.
Expand Down
22 changes: 22 additions & 0 deletions test_six.py
Original file line number Diff line number Diff line change
Expand Up @@ -934,6 +934,28 @@ def __bytes__(self):
assert getattr(six.moves.builtins, 'bytes', str)(my_test) == six.b("hello")


def test_hasattr():
class MyTest():
@property
def no_error(self):
pass

@property
def div_error(self):
raise ZeroDivisionError

@property
def attribute_error(self):
raise AttributeError

my_test = MyTest()
assert six.hasattr(my_test, "no_error")
assert not six.hasattr(my_test, "doesnotexist")
assert not six.hasattr(my_test, "attribute_error")
with py.test.raises(ZeroDivisionError):
six.hasattr(my_test, "div_error")


class EnsureTests:

# grinning face emoji
Expand Down