Created
January 21, 2009 17:52
-
-
Save gvx/50070 to your computer and use it in GitHub Desktop.
Simple module simulation
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
#namespace | |
#By Robin Wellner (gvx) | |
#I hereby waive copyright and related or neighboring rights to this work | |
#See the Creative Commons Zero Waiver at <http://creativecommons.org/publicdomain/zero/1.0/> | |
#Simulation of modules containing one or more function/class/object. | |
#Warning: modules are named differently than what you would expect. | |
def namespace(name): | |
class namespace: | |
def __init__(self, obj): | |
setattr(self, name, obj) | |
try: | |
obj.__name__ = name | |
except: | |
pass | |
def __repr__(self): | |
n = ', '.join(item for item in dir(self) if item not in dir(namespace)) | |
return 'namespace (%s)' % n | |
def __call__(self, name): | |
def x(obj): | |
setattr(self, name, obj) | |
try: | |
obj.__name__ = name | |
except: | |
pass | |
return self | |
return x | |
return namespace |
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
#Examples | |
#I hereby waive copyright and related or neighboring rights to this work | |
#See the Creative Commons Zero Waiver at <http://creativecommons.org/publicdomain/zero/1.0/> | |
from namespace import namespace | |
#Use as a decorator | |
@namespace('degrees') | |
def math(rad): | |
return rad * 57.295779513082323 | |
print math.degrees(1) | |
#57.295779513082323 | |
print repr(math) | |
#namespace (degrees) | |
#Object example: | |
sys = namespace('maxint')(256) | |
print sys.maxint | |
#256 | |
#Module tree example: | |
@namespace('ScrolledMessageDialog') | |
@namespace('dialogs') | |
@namespace('lib') | |
def wx(parent, text, caption): | |
return (parent, caption + ': ' + text) | |
print wx.lib.dialogs.ScrolledMessageDialog(None, 'Hello World', | |
'And now for something completely different') | |
#(None, 'And now for something completely different: Hello World') | |
#Multiple objects in one namespace example: | |
@namespace('python') | |
def monty(string): | |
return 'This is a test: ' + string | |
@namespace('spam') | |
def monty(): | |
return 6 | |
print repr(monty) | |
#namespace (python, spam) | |
print monty.python('1 2 3') | |
#This is a test: 1 2 3 | |
print monty.spam | |
#6 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment