B3.2: multiple text script

Hi all :slight_smile:

I have a 17 Gazillion lines text script in my .blend and i was wondering wether it is possible to create another text script in blender ( not from a file but integrated in blender ) that would contain the functions i use.

something like:
TEXT1:

import bpy

def MyAdd(a,b)
    return(a+b)

and
TEXT2:

import bpy
import TEXT1

print(MyAdd(19,33))

Just like it is done in a C or C++ IDE…
Is it possible and if yes, how can it be done ?

Thanks and happy blending ! :smiley:

I made a script a while back that demonstrates how to dynamically create a new script from copied data.

Hi @RPaladin :smiley:

This looks interresting :smiley:

You mean i should find the TEXT1 object, copy it and paste it dynamically in the main code at run ?

This would be a real simple solution ! But wont it modify for real the main code ?

I have to dig in this :wink:

Thanks and happy blending !

Hi. I think I misunderstood what you originally wanted (I thought you wanted to dynamically create a second script). To access an existing secondary script, and get and run a function from it, you need to state the script as a module, so that it can be imported as a module.

TEXT1.py

import bpy

def MyAdd(a,b):
    return(a+b)

TEXT2.py

import bpy

TEXT1 = bpy.data.texts["TEXT1.py"].as_module()
print(TEXT1.MyAdd(19,33))
3 Likes

Wah :smiley:

Yes it seems this is what i need :wink:

I come back soon to confirm :stuck_out_tongue:

Thanks @RPaladin !
And happy blending !

This is insanely simple !!!
And works like a charm !

And i guess that those ‘include’ can be nested just as in H files of a C project ?

I was just wondering wether it would be possible to simply use MyAdd(19,33) instead of TEXT1.MyAdd(19,33) ?

Thanks a lot @RPaladin :smiley:
This will make my code muuuuuuuuch clearer !

Happy blending !

Both of your questions have the same answer - they need to be imported somehow. In this case with as_module(). If you’d prefer to use abbreviations, I suggest making variable pointers. Like so:

import bpy
TEXT1 = bpy.data.texts["TEXT1.py"].as_module()
MyAdd = TEXT1.MyAdd
print(MyAdd(19,33))
1 Like

wow :open_mouth:

As you probably noticed, i’m i noob at python…

I didn’t know this was this simple to do !
And from what i can remember, it is possible to list all functions in a module. Therefore, automate the suppression of ‘TEXT1’…

Raaah this looks great ! :smiley:
I don’t have time for now to try all this out but be sure i be back very soon with more questions @RPaladin :smiley:

Thanks a LOT !

And happy blending !