次の方法で共有


IronPython: Keyword Argument to Set .NET Property/Field

Use keyword arguments to set properties or fields… you likely ask the question: where can we do this? IronPython allows it in the constructor call, the call against the .NET type. Such keyword should be the name of public field, or property (which is not read-only). After creating the object instance, each keyword argument value is then set to the corresponding field or property. Note keyword arguments can be used for the constructor parameters as usual.

The IronPython code below is to monitor any python file change under the directory "C:\temp". I used this special argument passing in the 2nd line.

import System
fsw = System.IO.FileSystemWatcher(r"C:\temp", Filter= "*.py" , IncludeSubdirectories = True, EnableRaisingEvents = True)
def on_changed(o,e): print e.ChangeType, e.FullPath
fsw.Changed += on_changed

System.Console.ReadLine()

FileSystemWatcher has three constructors (see below). The code uses the second one (not the third one)."c:\temp" is positional argument for "path"; the next 3 keywords arguments are transformed to the property (Filter/IncludeSubdirectories/…) assignments after the object creation.

  • public FileSystemWatcher();
  • public FileSystemWatcher(string path);
  • public FileSystemWatcher(string path, string filter);

I am not going to argue whether this feature is good or bad. You may find it handy in some places. The user could get confused when the constructor parameter name is same as the field/property name (Although it is unlikely as most libraries are following the .NET framework guideline: property name starts with the capital character, while the parameter name does opposite). One of our summer interns also proposed to extend this feature to event setting as keyword argument. It is currently not supported, not sure whether it will ever come in the future.

Note this code above actually doe not work in IronPython 2.0 alpha 4 (due to bugs). The upcoming 2.0 alpha5 will have the fix.