添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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?

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.

You're exactly right - clr.AddReference loads the assembly, and import makes the names available. – Jeff Hardy Dec 2, 2013 at 17:16

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.