[Python-Dev] New miniconf module
Michael Foord
fuzzyman at voidspace.org.uk
Thu Jul 27 13:46:04 CEST 2006
Armin Rigo wrote:
> Hi,
>
> On Thu, Jul 27, 2006 at 03:39:39AM -0400, Sylvain Fourmanoit wrote:
>
>> Having JSON there would indeed be nice: In fact, I recall being initially
>> surprised it was not supported by the standard library.
>>
>> But is there a need to choose? Why not have both? The miniconf approach
>> has its advantages and differences:
>>
>
> I support this point of view: miniconf fills the hole that the stdlib
> leaves for a safe and cross-version dumper/loader for simple objects
> using the Python syntax. In the same spirit, maybe it could be slightly
> re-oriented towards a dumper/loader for more than config files; for
> example, it could provide a safe inverse of repr() for common built-in
> types. Such a functionality has been discussed here a few times if I
> remember correctly, but the code in miniconf is very close to providing
> it.
>
ConfigObj [1] gained an 'unrepr' mode a while back. The code is simple,
and originally came from CherryPy.
It can (safely) unrepr basic datatypes.
import compiler
def getObj(s):
s = "a=" + s
p = compiler.parse(s)
return p.getChildren()[1].getChildren()[0].getChildren()[1]
class UnknownType(Exception):
pass
class Builder:
def build(self, o):
m = getattr(self, 'build_' + o.__class__.__name__, None)
if m is None:
raise UnknownType(o.__class__.__name__)
return m(o)
def build_List(self, o):
return map(self.build, o.getChildren())
def build_Const(self, o):
return o.value
def build_Dict(self, o):
d = {}
i = iter(map(self.build, o.getChildren()))
for el in i:
d[el] = i.next()
return d
def build_Tuple(self, o):
return tuple(self.build_List(o))
def build_Name(self, o):
if o.name == 'None':
return None
if o.name == 'True':
return True
if o.name == 'False':
return False
# An undefinted Name
raise UnknownType('Undefined Name')
def build_Add(self, o):
real, imag = map(self.build_Const, o.getChildren())
try:
real = float(real)
except TypeError:
raise UnknownType('Add')
if not isinstance(imag, complex) or imag.real != 0.0:
raise UnknownType('Add')
return real+imag
def build_Getattr(self, o):
parent = self.build(o.expr)
return getattr(parent, o.attrname)
def build_UnarySub(self, o):
return -self.build_Const(o.getChildren()[0])
def build_UnaryAdd(self, o):
return self.build_Const(o.getChildren()[0])
def unrepr(s):
if not s:
return s
return Builder().build(getObj(s))
HTH
Michael Foord
[1] http://www.voidspace.org.uk/python/configobj.html
>
> A bientot,
>
> Armin
> _______________________________________________
> Python-Dev mailing list
> Python-Dev at python.org
> http://mail.python.org/mailman/listinfo/python-dev
> Unsubscribe: http://mail.python.org/mailman/options/python-dev/fuzzyman%40voidspace.org.uk
>
>
More information about the Python-Dev
mailing list