def does(instance, role): ''' Returns True if %{instance} supports the role %(role). %(class) can be instance, class or string. %(role) can be instance, class or string. Example: has_comment_support = does(self, 'Comments') ''' meta = MetaRole() return meta.__does__(instance, role)
class Role(CommonRole): ''' ------------------------------------------- --- ---- - - - - - Base class for Roles. New roles inherits from this. ---------------------------------------------------------------------- ''' meta = MetaRole() def __init__(self, instance, **kwargs): self.meta.init_attributes(self, for_class=instance, role_args=kwargs) def check_requires(self, with_class): ''' The role can have a 'requires' attribute containing a list of attribute-names that the user class has to implement to do the role. This method will check that all requirements are fulfilled. ''' # Check if we have requirements at all if not hasattr(self, '__requires__'): return True if not len(self.__requires__): return True for requirement in self.__requires__: if not hasattr(with_class, requirement): raise ClassDoesNotFulfillRequirement(requirement) return True
def has_role(instance, *args, **kwargs): ''' Applies the roles %{args} to your class instance. %{instance} must be a class instance object. %{args} must be a list of class objects, not instantiated classes. Example: has_role(self, RoleClass) has_role(self, RoleClass, OtherRoleClass) ''' meta = MetaRole() meta.apply(instance, *args, **kwargs)
# Now compose it and get the conflict: class FooBarWithConflict2(object): pass foobarwithconflict2_conflicts = 0 try: has_role(FooBarWithConflict2, rFooBar) except RoleConflictDetected: foobarwithconflict2_conflicts = 1 from roleplay.meta import MetaRole meta = MetaRole() assert foobarwithconflict2_conflicts ## now compose, and let it get dis-ambiguated class FooBarWithOutConflict2(object): def baz(self): return "FooBar::With::Out::Conflict2::baz" foobarwithoutconflict2_resolved = 1 try: has_role(FooBarWithOutConflict2, rFooBar) except RoleConflictDetected: