1
votes

My application can be extended via IronPython scripts provided by the user.

  • First, I create a new ScriptScope.
  • Using that script scope, I run a short setup script that performs some convenience imports.
  • Finally, I run all user scripts in the prepared scope.

The setup script looks like this:

import clr
import System
from System import Exception
from System import Math
clr.ImportExtensions(System.Linq.Enumerable)

The idea is that user scripts can use common types like Math or Exception without having to import them first.

I would also like LINQ to work out of the box, so I added the last line to the setup script. However, while the regular imports work fine, the extension import does not. From what I could figure out, regular imports become part of the script scope and thus are available to any subsequent script running in the same scope. Extension imports, however, seem to work differently.

So my question is: how can a script I execute use LINQ without having to explicitly import the extension methods?

Note: There are a lot of scripts, many of which contain only a single expression. So I would rather avoid the performance penalty of automatically prefixing each script with the extension import.

1
Have you had a look at mail.python.org/pipermail/ironpython-users/2011-May/014829.html ? Could this explain the behavior you are facing? - Simon Opelt
@Simon: Thanks for the link, that certainly explains the behavior. Now, if only they implemented what's suggested in the last post there: "a clr.ImbueTypeWithExtensions(cls, extcls) method that ... made the extensions available everywhere." - Daniel Wolf
I don't believe there's a way to do what you're asking. Can you please create an issue (ironpython.codeplex.com/WorkItem/Create) describing what you would like to see? - Jeff Hardy

1 Answers

0
votes

Look at the IL for a LINQ statement in Reflector or ILSpy. LINQ is compiler magic at work that turns the statement into a bunch of classes and method calls. You are never going to get LINQ to work. Your best bet is a wrapper class that does some LINQ related work for you. Focus on the actual use case you are trying to provide for and provide Helper methods to get the work done.