Including External Code Files

NOOB Question: If I have some Python code in a file called MyCodeLibrary.py, how do I include the code in that file so I can use the functions defined there in my current code file?

If it’s all IronPython 2.7 compliant code, you can simply put your module or individual Python files into C:\Users\<username>\AppData\Roaming\McNeel\Rhinoceros\7.0\scripts.
Once you’ve restarted Rhino, you should be able to import from them.

@diff-arch - What if the file is on a different drive, say a server drive that has a drive letter mapped to it? How can I manually load that code by directing it to a specific path and file?

I just found it. Posting it here for others.

Can I omit the ‘import Function’ to import all functions from MyCodeFile? If not how do I load all functions from that file?

import sys
sys.path.append(r'D:\MyFolder')
from MyCodeFile import Function
import MyCodeFile
1 Like

@diff-arch - There was a little more to it than that. Documenting it here so other’s can solve the same issue faster…

sys.path.append(r'C:\Files\\My Python Scripts')
from MyScriptFile import *

Yes this works but as your code grows in size it can lead to strange bugs as you are importing lots of function names on top of the file you are working on. Many coders recommend explicitly importing only the functions you need e.g. from MyScriptFile import my_big_function, my_little_function or just importing import MyScriptFile and letting autocomplete help you out finding the individual functions inside.

To go further down the rabbit hole you can define an __all__ parameter in the imported file to say which functions should be included in from MyScriptFile import *

:slight_smile:

2 Likes

Great info!