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

root/trunk/cherrypy/lib/__init__.py

Revision 1794 (checked in by fumanchu, 8 months ago)

More-meaningful config syntax errors.

  • 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_Subscript(self, o):
49         expr, flags, subs = o.getChildren()
50         expr = self.build(expr)
51         subs = self.build(subs)
52         return expr[subs]
53    
54     def build_CallFunc(self, o):
55         children = map(self.build, o.getChildren())
56         callee = children.pop(0)
57         kwargs = children.pop() or {}
58         starargs = children.pop() or ()
59         args = tuple(children) + tuple(starargs)
60         return callee(*args, **kwargs)
61    
62     def build_List(self, o):
63         return map(self.build, o.getChildren())
64    
65     def build_Const(self, o):
66         return o.value
67    
68     def build_Dict(self, o):
69         d = {}
70         i = iter(map(self.build, o.getChildren()))
71         for el in i:
72             d[el] = i.next()
73         return d
74    
75     def build_Tuple(self, o):
76         return tuple(self.build_List(o))
77    
78     def build_Name(self, o):
79         if o.name == 'None':
80             return None
81         if o.name == 'True':
82             return True
83         if o.name == 'False':
84             return False
85        
86         # See if the Name is a package or module. If it is, import it.
87         try:
88             return modules(o.name)
89         except ImportError:
90             pass
91        
92         # See if the Name is in __builtin__.
93         try:
94             import __builtin__
95             return getattr(__builtin__, o.name)
96         except AttributeError:
97             pass
98        
99         raise TypeError("unrepr could not resolve the name %s" % repr(o.name))
100    
101     def build_Add(self, o):
102         left, right = map(self.build, o.getChildren())
103         return left + right
104    
105     def build_Getattr(self, o):
106         parent = self.build(o.expr)
107         return getattr(parent, o.attrname)
108    
109     def build_NoneType(self, o):
110         return None
111    
112     def build_UnarySub(self, o):
113         return -self.build(o.getChildren()[0])
114    
115     def build_UnaryAdd(self, o):
116         return self.build(o.getChildren()[0])
117
118
119 def unrepr(s):
120     """Return a Python object compiled from a string."""
121     if not s:
122         return s
123    
124     try:
125         import compiler
126     except ImportError:
127         # Fallback to eval when compiler package is not available,
128         # e.g. IronPython 1.0.
129         return eval(s)
130    
131     p = compiler.parse("__tempvalue__ = " + s)
132     obj = p.getChildren()[1].getChildren()[0].getChildren()[1]
133    
134     return _Builder().build(obj)
135
Note: See TracBrowser for help on using the browser.

Hosted by WebFaction

Log in as guest/cpguest to create tickets