Loading modules in IronPython
Asked Answered
I

1

5

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?

Irreducible answered 29/11, 2013 at 11:19 Comment(0)
I
7

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

Irreducible answered 29/11, 2013 at 11:19 Comment(1)
You're exactly right - clr.AddReference loads the assembly, and import makes the names available.Doorway

© 2022 - 2024 — McMap. All rights reserved.