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

fix hasattr() crashing when used on DottedDict #14

Open
wants to merge 6 commits 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
10 changes: 10 additions & 0 deletions .deepsource.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
version = 1

test_patterns = ["dotted/test/*"]

[[analyzers]]
name = "python"
enabled = true

[analyzers.meta]
runtime_version = "3.x.x"
22 changes: 18 additions & 4 deletions dotted/collection.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,14 @@ def split_key(key, max_keys=0):
return result


class KeyOrAttributeError(KeyError, AttributeError):
"""
Exception that should be raised when it's ambiguous whether
a key or an attribute was accessed
"""
pass


@add_metaclass(ABCMeta)
class DottedCollection(object):
"""Abstract Base Class for DottedDict and DottedDict"""
Expand Down Expand Up @@ -263,14 +271,20 @@ def __getitem__(self, k):
key = self.__keytransform__(k)

if not isinstance(k, basestring) or not is_dotted_key(key):
return self.store[key]
try: # since __getattr__ is the same as __getitem__, it can be
return self.store[key] # that an attribute is requested here
except KeyError as e: # for instance, if hasattr is called
raise KeyOrAttributeError(e)

my_key, alt_key = split_key(key, 1)
target = self.store[my_key]
try:
target = self.store[my_key]
except KeyError as e:
raise KeyOrAttributeError(e)

# required by the dotted path
if not isinstance(target, DottedCollection):
raise KeyError('cannot get "{0}" in "{1}" ({2})'.format(
raise KeyOrAttributeError('cannot get "{0}" in "{1}" ({2})'.format(
alt_key,
my_key,
repr(target)
Expand Down Expand Up @@ -368,4 +382,4 @@ def default(self, obj):
if isinstance(obj, DottedCollection):
return obj.store
else:
return json.JSONEncoder.default(obj)
return json.JSONEncoder.default(self, obj)