Question

I am confused about the two ways to import modules in IronPython.

On the one hand, the tutorial documentation that comes with IronPython 2.7.4 states that you can do it using the regular import syntax:

import System
from System import Xml

This works as I would expect.

On the other hand, many resources on the internet state that the way to import modules is by using the clr module like so:

import clr
clr.AddReference("System.Xml")

What is the difference between the two methods?

Était-ce utile?

La solution

While I was researching this question I stumbled across what I believe to be the answer (this is from trial and error alone so if I'm wrong I'd be happy to be corrected!)

The import statement in Python is more analogous to a using <namespace> statement in C#. you still need to load the relevant .dll assembly. C# does this at compile-time by using references; IronPython by default includes standard CLR references, which is why it is immediately possible to import System.Xml

However, if you want to load a .dll that is not included by default in IronPython, you must use clr.AddReference("myAssembly.dll") and then use the import statement to import the module.

For example:

import clr
clr.AddReferenceToFileAndPath(r"..\lib\umbraco.dll")
import umbraco

The umbraco module is now accessible to IronPython

N.B. The Visual Studio plugin "Python Tools" allows you to add references to a Python project, but the above steps are still necessary to use a reference.

Visual Studio projects support adding references to projects and extensions. Typically they indicate dependencies between projects and are used to provide IntelliSense at design time or linking at compile time. Python Tools for Visual Studio also uses references in a similar fashion, but due to the dynamic nature of Python they are primarly used at design time to provide improved IntelliSense.

Link

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top