namespace/dictionary quandry

Alex Martelli aleaxit at yahoo.com
Wed Sep 22 19:18:52 CEST 2004


Jack Carter <jcarter at johmar.engr.sgi.com> wrote:
   ...
> The solution it would seem would be to do the evaluation
> later within the called function. That way I could assume
> that all failed eval()'ed names are literals meant for my
> command and not a python variable/name.
> 
> If this makes sense, the problem I need to solve is how to
> deliver the correct namespace dictionary to the called function
> so I can invoke eval with it.
> 
> Does this make sense?

Not very, but then I didn't follow the previous LONG posts on this
thread, so I'll just answer this specific question and hope it helps.
I'll assume the known variable-names are in some dictionary (such as a
locals() or globals() or vars(something)):

class WeirdNamespace:
    def __init__(self, d): self.d = d
    def __getitem__(self, n): return self.d.get(n,repr(n))

voila: if n is a key in dict d, this returns the corresponding value,
otherwise it returns n suitably quoted.  Just pass to eval a
WeirdNamespace(d) rather than the bare d.

It appears to me your user interface is courting trouble: if I mispell
'variablename' as 'varaiblename' I end up creating a file I didn't mean
to rather than getting a clean error about unknown variable names.  But
I'll assume you know your users better than I do and that they _do_
really desire with all their hearts this unholy confusion between
variables and constants...


Alex



More information about the Python-list mailing list