[Ironpython-users] Simulating Python's scoping at the DLR level

Curt Hagenlocher curt at hagenlocher.org
Tue Dec 20 17:03:31 CET 2011

I don't think you can replicate Python's semantics exactly, because Python
compiles an entire block at once but your scope would only see reads and
writes sequentially as they happen. For instance, in Python, the following
code will generate an error:

a = 1
def test():
    a = 2

That's because the assignment to "a" in "test" causes Python to consider
"a" to be a local variable for the duration of the entire function. This
isn't something you can duplicate with a ScriptScope-level component.

Having said that, and with the disclaimer that it's been over two years
since I've looked at DLR source code, here's what I think you want to do:

1. Given that you have two scopes -- a "global" scope and a "local" scope,
think carefully about the behavior that you want to define for the eight
possible cases of (read/write)(present/absent in local
scope)(present/absent in global scope).
2. Implement an IDynamicMetaObjectProvider which implements this behavior
on top of two other IDMOPs.
3. Using the global and local ScriptScopes (or Scopes, or ScopeStorages),
construct an instance of this new type.
4. Pass this object to ScriptRuntime.CreateScope to create a new
ScriptScope from the combined child scopes.

The delegating IDMOP can probably be built pretty efficently by being smart
about the error/fallback.
On Tue, Dec 20, 2011 at 12:15 AM, Doug Blank <doug.blank at gmail.com> wrote:

> What would be a good way to simulate Python's scoping rules at the DLR
> level?
> For example, if I were running two DLR-based scripts, I can just use
> the same ScriptScope for both to have shared globals.
> But how would you replicate Python's exact idea of a local environment
> in each, while falling back to a shared, global one, in DLR-based
> code?
> I guess I'm looking for something like:
>   Execute("x = y + z", local1, globals);
>    Execute("x = y + z", local2, globals);
> where local1, local2, and globals are dictionaries, and "x" would end
> up being added to the local dictionaries, and "y" and "z" would be
> looked for first in local1 or 2, then a shared globals.
> Any suggestions?
> Thanks!
> -Doug
> _______________________________________________
> Ironpython-users mailing list
> Ironpython-users at python.org
> http://mail.python.org/mailman/listinfo/ironpython-users
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/ironpython-users/attachments/20111220/59e89bb9/attachment.html>

More information about the Ironpython-users mailing list