> -----Original Message-----
> From: sqlalchemy@googlegroups.com 
> [mailto:sqlalch...@googlegroups.com] On Behalf Of Chris Withers
> Sent: 08 July 2010 11:21
> To: sqlalchemy@googlegroups.com
> Subject: Re: [sqlalchemy] Comparable properties
> 
> King Simon-NFHD78 wrote:
> >   @hybrid
> >   def is_visible(self):
> >     return (self.enabled == True) & (self.is_deleted == False)
> 
> Yeah, having to write something that works as both plain python and a 
> sql layer construct seems a little brittle.
> 
> I wonder if a decorator could be knocked up which would let you do:
> 
> def _python_is_visible(self):
>    return (self.enabled and not self.is_deleted)
> 
> def _sql_is_visible(self):
>    return (self.enabled == True) & (self.is_deleted == False)
> 
> is_visible = some_magic(_python_is_visible,_sql_is_visible)
> 
> cheers,
> 
> Chris
> 

Untested beyond what you see here:


class MagicProperty(object):
    def __init__(self, instance_version, class_version=None):
        self._instance_version = instance_version
        self._class_version = class_version
        
    def __get__(self, instance, owner):
        if instance is not None:
            return self._instance_version(instance)
        else:
            return self._class_version(owner)

    def with_class(self, f):
        self._class_version = f
        

class Test(object):
    def from_instance(self):
        return 'This was accessed via the instance'

    def from_class(self):
        return 'This was accessed via the class'

    magic = MagicProperty(from_instance, from_class)


class Test2(object):
    @MagicProperty
    def magic(self):
        return 'This was accessed via the instance'

    @magic.with_class
    def from_class(self):
        return 'This was accessed via the class'


if __name__ == '__main__':
    print Test.magic
    t = Test()
    print t.magic


    print Test2.magic
    t2 = Test2()
    print t2.magic



Simon

-- 
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To post to this group, send email to sqlalch...@googlegroups.com.
To unsubscribe from this group, send email to 
sqlalchemy+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en.

Reply via email to