Download Install Tutorial Docs FAQ Tools WikiLicense Team IRC Planet Involvement Shop Book

root/tags/cherrypy-3.0.0/cherrypy/lib/__init__.py

Revision 1456 (checked in by fumanchu, 2 years ago)

Fix for #609 (Support for IronPython? 1.0).

  • Property svn:eol-style set to native
Line 
1 """CherryPy Library"""
2
3 import sys as _sys
4
5
6 def modules(modulePath):
7     """Load a module and retrieve a reference to that module."""
8     try:
9         mod = _sys.modules[modulePath]
10         if mod is None:
11             raise KeyError()
12     except KeyError:
13         # The last [''] is important.
14         mod = __import__(modulePath, globals(), locals(), [''])
15     return mod
16
17 def attributes(full_attribute_name):
18     """Load a module and retrieve an attribute of that module."""
19    
20     # Parse out the path, module, and attribute
21     last_dot = full_attribute_name.rfind(u".")
22     attr_name = full_attribute_name[last_dot + 1:]
23     mod_path = full_attribute_name[:last_dot]
24    
25     mod = modules(mod_path)
26     # Let an AttributeError propagate outward.
27     try:
28         attr = getattr(mod, attr_name)
29     except AttributeError:
30         raise AttributeError("'%s' object has no attribute '%s'"
31                              % (mod_path, attr_name))
32    
33     # Return a reference to the attribute.
34     return attr
35
36
37 # public domain "unrepr" implementation, found on the web and then improved.
38
39 class _Builder:
40    
41     def build(self, o):
42         m = getattr(self, 'build_' + o.__class__.__name__, None)
43         if m is None:
44             raise TypeError("unrepr does not recognize %s" %
45                             repr(o.__class__.__name__))
46         return m(o)
47    
48     def build_CallFunc(self, o):
49         callee, args, starargs, kwargs = map(self.build, o.getChildren())
50         return callee(args, *(starargs or ()), **(kwargs or {}))
51    
52     def build_List(self, o):
53         return map(self.build, o.getChildren())
54    
55     def build_Const(self, o):
56         return o.value
57    
58     def build_Dict(self, o):
59         d = {}
60         i = iter(map(self.build, o.getChildren()))
61         for el in i:
62             d[el] = i.next()
63         return d
64    
65     def build_Tuple(self, o):
66         return tuple(self.build_List(o))
67    
68     def build_Name(self, o):
69         if o.name == 'None':
70             return None
71         if o.name == 'True':
72             return True
73         if o.name == 'False':
74             return False
75        
76         # See if the Name is a package or module
77         try:
78             return modules(o.name)
79         except ImportError:
80             pass
81        
82         raise TypeError("unrepr could not resolve the name %s" % repr(o.name))
83    
84     def build_Add(self, o):
85         real, imag = map(self.build_Const, o.getChildren())
86         try:
87             real = float(real)
88         except TypeError:
89             raise TypeError("unrepr could not parse real %s" % repr(real))
90         if not isinstance(imag, complex) or imag.real != 0.0:
91             raise TypeError("unrepr could not parse imag %s" % repr(imag))
92         return real+imag
93    
94     def build_Getattr(self, o):
95         parent = self.build(o.expr)
96         return getattr(parent, o.attrname)
97    
98     def build_NoneType(self, o):
99         return None
100    
101     def build_UnarySub(self, o):
102         return -self.build_Const(o.getChildren()[0])
103    
104     def build_UnaryAdd(self, o):
105         return self.build_Const(o.getChildren()[0])
106
107
108 def unrepr(s):
109     """Return a Python object compiled from a string."""
110     if not s:
111         return s
112    
113     try:
114         import compiler
115     except ImportError:
116         # Fallback to eval when compiler package is not available,
117         # e.g. IronPython 1.0.
118         return eval(s)
119    
120     p = compiler.parse("a=" + s)
121     obj = p.getChildren()[1].getChildren()[0].getChildren()[1]
122    
123     return _Builder().build(obj)
124
Note: See TracBrowser for help on using the browser.

Hosted by WebFaction

Log in as guest/cpguest to create tickets