Could Emacs be rewritten in Python?
Bernhard Herzog
bh at intevation.de
Wed Apr 16 12:52:44 EDT 2003
Alexander Schmolck <a.schmolck at gmx.net> writes:
[description how dynamic scoping could be put into the python syntax]
> Maybe this is stupid and maybe it doesn't work and no I haven't
> thought deeply about packages and classes so far (which as Beni
> already mentioned seem to render a literal mapping of CL's approach
> unattractive)
Python is often quite explicit about which namespaces a variable come
from (e.g. instance variables require an explicit self; the global
statement). The same approach could be taken with dynamic scopes which
could require an explicit dynamic scope and that can even be implemented
in python itself:
import inspect
class Scope:
def __init__(self, base, defaults):
if base is not None:
self.__dict__.update(base.__dict__)
self.__defaults = defaults
def __getattr__(self, attr):
if self.__defaults is not None:
try:
return self.__defaults[attr]
except KeyError:
pass
raise AttributeError, attr
# Name for local variables holding dynamic scopes
scope_var_name = "scope"
def dynscope():
"""Return a new dynamic scope for use in the caller's frame"""
caller = inspect.currentframe().f_back
frame = caller.f_back
while frame:
base = frame.f_locals.get(scope_var_name)
if isinstance(base, Scope):
break
frame = frame.f_back
else:
base = None
scope = Scope(base, caller.f_globals)
return scope
# Example usage
# default value for dynamically scoped variable
variable = "default"
def print_variable():
"""Print the value of the dynamically scoped variable 'variable'"""
scope = dynscope()
print "dynamically scoped variable:", scope.variable
def intermediate():
print_variable()
def shadow_variable():
# define a dynamic scope with a value for 'variable'
scope = dynscope()
scope.variable = "shadowed"
#Call use_variable indirectly
intermediate()
if __name__ == "__main__":
# Calling print_variable directly should print "default" as value
print_variable()
# Calling print_variable through shadow_variable should print
# "shadowed" as value
shadow_variable()
Bernhard
--
Intevation GmbH http://intevation.de/
Sketch http://sketch.sourceforge.net/
MapIt! http://www.mapit.de/
More information about the Python-list
mailing list