Advanced Python Tips

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

20170621-1830 - 20170621-1900

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


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):

a = A()
a.__class__.f = property(lambda self: 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))