Im trying to create a class that has a time remaining property and executing functions within it reduces this time. Here is the code
JavaScript
x
24
24
1
class TestClass:
2
def __init__(self):
3
self.time_remaining = 240
4
5
@staticmethod
6
def time_taken(start):
7
return (datetime.now() - start).seconds
8
9
def with_timeout(f):
10
@wraps(f)
11
def wrapper(self, *args, **kwargs):
12
start = datetime.now()
13
result = f(self, *args, **kwargs)
14
self.time_remaining = (
15
self.time_remaining - TestClass.time_taken(start)
16
)
17
return result
18
19
return wrapper
20
21
@with_timeout
22
def do_something(self, param):
23
# DO Something
24
Then when i instantiaite the class and use do_something
like so:
JavaScript
1
3
1
test_class = TestClass()
2
test_class.do_something("param")
3
It works as expected. However when i run pylint on the code i get an error:
JavaScript
1
2
1
pylint: not-callable / f is not callable
2
Is this a false positive or is there a better way to write this functionality?
Thanks
Advertisement
Answer
Thanks for the comments. Moving the method outside the class was what was required as self is bound depending on how a method is called, not where it is defined so the decorator doesn’t need to be defined within the class to have access to self:
JavaScript
1
22
22
1
def time_taken(start):
2
return (datetime.now() - start).seconds
3
4
def with_timeout(f):
5
@wraps(f)
6
def wrapper(self, *args, **kwargs):
7
start = datetime.now()
8
result = f(self, *args, **kwargs)
9
self.time_remaining = self.time_remaining - time_taken(start)
10
return result
11
12
return wrapper
13
14
15
class TestClass:
16
def __init__(self):
17
self.time_remaining = 240
18
19
@with_timeout
20
def do_something(self, param):
21
# DO Something
22