TransWikia.com

Using same name for attribute and getter

Stack Overflow Asked by janpeterka on February 13, 2021

I have following class/model:

class Recipe(db.Model):
    ...
    user_id = db.Column(db.ForeignKey(("users.id")), nullable=False, index=True)
    author = db.relationship("User", uselist=False, back_populates="diets")
    ...

    # Permissions
    def can_view(self, user = None) -> bool:
        if user is None:
            user = current_user
        return self.author == user

I can use recipe.can_view() or recipe.can_view(some_user), but I want to be able to call recipe.can_view instead of recipe.can_view(), and I don’t know what’s a nice solution for that.

Thanks

One Answer

Looks like I cannot do that (at least without making some mess).

So, I went with the solution proposed by @zvone in comments:

I would go with can_view(user) and can_current_user_view

So, my code is:

    def can_view(self, user) -> bool:
        return self.is_author(user) or user.is_admin or self.is_public

    @property
    def can_current_user_view(self) -> bool:
        return self.can_view(user=current_user)

Answered by janpeterka on February 13, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP