Skip to content

Add a class to manage the context of a interaction with Python and simplify the variable exchanging #380

Closed

Description

@yagweb

"eval" and "exec" are the most frequently used methods when interacting with Python. However, this two methods implemented here are hard to use because maintain the global variable dictionary and local variable dictionary is a tedious and repeated work.

The nature of the problem lies in the variable exchanging between .NET and Python.

I think a scope class can be added to manage the context of a interaction with Python and simplify the variable exchanging.
A Scope should act like a Python Module in .NET. In the Scope class, many python functions can be wrapped to operate with the locals and globals for easy-to-use and speeding up.

For example, the eval example provided in that PR,

dynamic sys = Py.Import("sys");
sys.attr1 = 100;
PyDict locals = new PyDict();
locals.SetItem("sys", sys);
locals.SetItem("a", new PyInt(10));
 
PythonEngine.Exec("c = sys.attr1 + a + 1", null, locals.Handle);
var c = locals.GetItem("c").AsManagedObject(typeof(Int32));

Console.WriteLine("c= {0}", c);

can be written as,

var ps = Py.Session('test')
sys = ps.Import("sys");
sys.attr1 = 100;
ps.SetLocal("a", 10);
ps.Exec("c = sys.attr1 + a + 1");   //pass
var c = ps.Get<System.Int32>("c");  //get the local variable and convert it to .NET type.

ps.Dispose(); 
or
ps.Suspend(); //use it later. Py.Session('test') will return it.

I implement a prototype of this proposal here to help discussion.

Activity

  1. yagweb commented on Feb 15, 2017

    @yagweb
    ContributorAuthor

    I think it's a better practice to avoid using RunString with one or two python statements in .NET code, because it is low runtime efficiency. This proposal and the proposal can help to achieve this goal.

  2. vmuriart commented on Feb 15, 2017

    @vmuriart
    Contributor

    Do you still need to initialize and finalize the engine? From your proposal it doesn't sound like it but looking at the tests you are initializing and finalizing it.

  3. yagweb commented on Feb 17, 2017

    @yagweb
    ContributorAuthor

    @vmuriart Thank you for your remind. I updated the unit test and removed the initialize and finalize methods. Updated some APIs and edit the description of this issue before.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions