Advanced Python Tips




Pay Notebook Creator: Roy Hyunjin Han0
Set Container: Numerical CPU with TINY Memory for 10 Minutes 0
Total0

20170621-1830 - 20170621-1900

In my pyramid app, I created the following shortcut to access the user instance corresponding to request.authenticated_userid:

request.authenticated_user

defined by

config.add_request_method(lambda request: M.User.get(
    request.database, request.authenticated_userid
), 'authenticated_user', reify=True)

I also have a pytest fixture that mimics a request instance using testing.DummyRequest. I wanted to add a property to the request instance that preserved the functionality of request.authenticated_user.

A quick search on StackOverflow provided some clues, which I have summarized in the following snippet.

In [2]:
class A(object):
    pass

a = A()
a.__class__.f = property(lambda self: 57)
a.f
Out[2]:
57

Returning to the issue at hand, I was able to apply the newfound knowledge to achieve the desired effect.

users_request.__class__.authenticated_user = property(
    lambda self: M.User.get(self.database, self.authenticated_userid))