Last active
August 29, 2015 14:20
-
-
Save htv2012/51ddef12c842269f4bf3 to your computer and use it in GitHub Desktop.
Demo: an object that after closed, is in invalid state. At this point, any method invocation will result in an exception unless that method is decorated. Output: http://codepad.org/BUssgQR3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import functools | |
def accessible_while_closed(func): | |
""" | |
A decorator to mark a function as available, even after the object | |
closed. | |
""" | |
func.accessible_while_closed = True | |
return func | |
class MarkAsClosed(object): | |
def _invalid_action(self, *args, **kwargs): | |
raise IOError('object closed') | |
def mark_as_closed(self): | |
for name in dir(self): | |
# Ignore private members | |
if name.startswith('_'): | |
continue | |
member = getattr(self, name) | |
# Ignore non-callable (i.e. data) members | |
if not callable(member): | |
continue | |
# Ignore those callable members decorated with | |
# accessible_while_closed | |
if getattr(member, 'accessible_while_closed', False): | |
continue | |
setattr(self, name, self._invalid_action) | |
class Foo(MarkAsClosed): | |
def close(self): | |
print 'Foo.close' | |
self.mark_as_closed() | |
def do_something(self): | |
print 'Foo.do_something' | |
@accessible_while_closed | |
def ok_when_closed(self, name): | |
print 'Foo.ok_when_closed, name =', name | |
f = Foo() | |
f.close() | |
f.ok_when_closed('Hai') # Should be OK | |
f.do_something() # Not OK |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment