Partager via


IronPython: import clr

clr is an IronPython built-in module, which provides some functionalities in order to interop with .NET. When writing "import clr" in a python module, it means you intend to leverage the .NET libraries. One classical example is python string's methods. In IronPython, python type str is implemented by the .NET type System.String. We can call System.String's methods on string objects after the line of "import clr" (see the example below); of course those python string methods are still available.

> ipy.exe
IronPython console: IronPython 2.0 (2.0.0.00) on .NET 2.0.50727.1378
Copyright (c) Microsoft Corporation. All rights reserved.
>>> s = "IronPython"
>>> s.upper()
'IRONPYTHON'
>>> s.ToUpper()
Traceback (most recent call last):
  File , line 0, in ##14
  File , line 0, in _stub_##15
AttributeError: 'str' object has no attribute 'ToUpper'

>>> import clr
>>> s.upper()                 # python method still works
'IRONPYTHON'
>>> s.ToUpper()               # works
'IRONPYTHON'

Such context change is per-python-module. Although lib.py (below) imports the clr module and app.py then imports the lib module, app.py will not see the .NET methods. Running this app.py under C-Python will fail (ImportError) due to the usage of the clr module in lib.py. But if we make lib.py platform-neutral next time, we are ensured that no change in app.py is needed in order to run it under both C-Python and IronPython.

# lib.py
import clr
def my_upper(s): return s.ToUpper()

# app.py
import lib
s = "hello world"
print lib.my_upper(s)        # print "HELLO WORLD"
#print s.ToUpper()           # AttributeError would throw