Announcements
Attention for Customers without Multi-Factor Authentication or Single Sign-On - OTP Verification rolls out April 2025. Read all about it here.

This looks like legal Python - why won't it run within the API?

william-c-anderson
Advocate

This looks like legal Python - why won't it run within the API?

william-c-anderson
Advocate
Advocate

Here's some Python code (which works as expected in, say, the Idle interpreter):

prog='def _square(x):\n\treturn x*x\n'
exec(prog)
sq = _square(42)
print(sq)

In Idle, this returns 1764 as expected. In the F360 API environment, it gets this result:

NameError: name '_square' is not defined

This is particularly frustrating when, in the VS Code debugger, I can see the name _square defined as a function in the left column.

 

What can I do to get exec() to work correctly in the API?

 

 

0 Likes
Reply
Accepted solutions (1)
448 Views
3 Replies
Replies (3)

william-c-anderson
Advocate
Advocate
Accepted solution

I've answered my own question: a scope identifier is needed, depending upon how deep you are in the module. One of the following should work:

prog='global _square\ndef _square(x):\n\treturn x*x\n'

or

prog='nonlocal _square\ndef _square(x):\n\treturn x*x\n'

BTW, I don't actually use this in my API code...

1 Like

kandennti
Mentor
Mentor

Hi @william-c-anderson .

 

I am a little interested.
What kind of scene is creating a function dynamically?

 

I can think of a scene where a method is dynamically added to the Fusion360 API object.

0 Likes

william-c-anderson
Advocate
Advocate

@kandennti -san, I'll answer your question when the add-in is finished - I've finally gotten it mostly working. Sorry to be so "mysterious" šŸ˜‰ I still need to resolve a few issues with the constraint engine to make it work the way I want it to.

Thanks for so much help!

0 Likes