Tonight I was asked an interesting question regarding IronPython (well, Python) and how it handles the loose files when executing. With languages like C#, everything is compiled into an assembly and you have namespaces in order to locate the classes. However, in Python it is a little bit different.
With python, files can be either compiled into an assembly, or left loose within a directory depending on what you want to do. If you have your files loose, then you will need to reference the different files (modulesclasses). In the example below, I have a Customer class in a file called CustomerFile.py. I then have a main method which creates the Customer and calls the method within a file called main.py. The code for the files are here:
print “Hello World!”
from customerfile import Customer
print ‘Hello World’
c = Customer()
print ‘Created Customer’
if __name__ == “__main__”:
In order for the main file to know about the Customer File, we use the syntax – from
It’s important that both files are located in a directory defined in the path search variable, by default it is the main directory and the Lib directory.
>>> import sys
>>> print sys.path
[‘.’, ‘…IronPython-2.0B2’, ‘…IronPython-2.0B2Lib’]
If for example, CustomerFile.py was moved into a directory called Customer within the main folder, we would need to add that to the path variable in order for IronPython to look in the directory for the file. The code below does this, note that before we can import os, we need to add a reference to the location of the standard library.
Now, when we call the same code, IronPython will also search the Customer directory. The path would now look something like this:
[‘.’, ‘IronPython-2.0B2’, ‘IronPython-2.0B2Lib’, ‘C:python25Lib’, ‘IronPython-2.0B2Customer’]
Not overly difficult, but I can see new users becoming confused by this.