Skip to content

Commit

Permalink
Merge pull request #2 from magniff/faster_get
Browse files Browse the repository at this point in the history
Faster __get__
  • Loading branch information
Aleksandr Koshkin committed Sep 25, 2018
2 parents acccada + 29be113 commit b22ba4e
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 3 deletions.
38 changes: 38 additions & 0 deletions benchs/simple.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import perf


from watch import WatchMe, ArrayOf, MappingOf
from watch.builtins import InstanceOf


class MyClass(WatchMe):
foo = ArrayOf(MappingOf(InstanceOf(str), InstanceOf(int)))


my_obj = MyClass()
foo = [{'a': 1, 'b': 2, 'c': 3, 'd': 4}]
my_obj.foo = foo


def bench_get():
return my_obj.foo


def bench_set():
my_obj.foo = foo


my_obj_missing = MyClass()


def bench_get_missing():
try:
my_obj_missing.foo
except AttributeError:
pass


runner = perf.Runner()
runner.bench_func("__get__", bench_get)
runner.bench_func("__set__", bench_set)
runner.bench_func("__get__missing", bench_get_missing)
8 changes: 5 additions & 3 deletions watch/attr_controllers.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,16 @@ def __getattr__(self, attr_name):

def __get__(self, obj, klass=None):
# when attr being looked up in class instead of instance
if klass is not None and obj is None:
# klass is always not None
if obj is None:
return self

if self.field_name not in obj.__dict__:
try:
return obj.__dict__[self.field_name]
except KeyError:
raise AttributeError(
"Object %s has no attribute '%s'." % (obj, self.field_name)
)
return obj.__dict__[self.field_name]

def __set__(self, obj, value):
obj.__dict__[self.field_name] = value
Expand Down

0 comments on commit b22ba4e

Please sign in to comment.