# How to create reusable Python component [closed]

This follows from Garrett's fantastic answer here: In Python, given x-value on 2D Bezier Curve, return y-value

(EDIT: question generalised as per suggestion)

Say we have a Python file Foo.py containing the function X(p,q)

I would like to set things up so that my scripts can call X(...), rather than have to copy-paste its definition into each script that wants to invoke it.

How to accomplish this? And where is the right place to put Foo.py?

• This question appears to be off-topic because it is about python module / package organization and nothing blender-specific. – CodeManX Apr 11 '14 at 15:30
• this question would be better suited for stack overflow – David Apr 11 '14 at 18:14
• This question seems on-topic because it requires a Blender-specific answer (see my and Pi's answers). – Garrett Apr 11 '14 at 19:52
• Glad to hear you liked that function I wrote! But perhaps you could streamline the question, so make it more generic and get rid of the references to getYfromXforBezierObject, NumPy, etc. You could just call the function foo(). It just seems like there's some extraneous details... – Garrett Apr 11 '14 at 19:57
• Sorry all, I have rewritten the question. I think that the question of "where to put the file" does have some specific 'Blender' relevance. (I can see that "How to access a function from another file" OTOH is a pure Python question") – P i Apr 11 '14 at 21:26

You could save the file into the site-packages directory, which is found by going to your Blender folder and then 2.70 > python > lib > python3.3 > site-packages.

Say your file is called "Foo.py" and has in it a function

def X(p,q):
return p + q


then, after saving it into site-packages, in the Blender text editor or console, you could use:

from Foo import X


I figured out what I need to do.

I have my own ~/Dev/BlenderScripts folder (as per http://wiki.blender.org/index.php/Doc:2.6/Manual/Introduction/Installing_Blender/DirectoryLayout)

I set File > User Prefs > Scripts to "/users/pi/Dev/BlenderScripts"

(Note: using ~ does seem to work but it doesn't show up on sys.path; I have filed a potential bug: https://developer.blender.org/T39680?workflow=create)

Then with the mouse over the 3-D view, I press F8, which reloads Python stuff.

Then I check in Blender's Python prompt by doing:

import sys
sys.path


And it will show up /users/pi/Dev/BlenderScripts/{ addons, modules, startup }

I then create modules/Foo.py, which contains function:

def X(p,q):
print( (p,q) )


Then from another script, or from Blender's Python prompt, I do:

from Foo import X
X(1,2)

• It appears that inside your scripts directory, there must be at least one of the directories: addons, modules or startup. And you must put the file into one of these. I know this is what you did, but could you make it more explicit (that part tripped me up)? – Garrett Apr 11 '14 at 19:48