Hi guys, a noob Python question here.
My scripts are becoming more complex and need better control. I have a few definitions in the script and need to have some variables that are accessible above them so I don’t have to return the value via the definition. What is the best approach?
I have used sticky as a simple workaround, but I am sure there are better options.
The issue here is that you’ve defined string as a global variable in the outer most scope, but in the setString() function you re-define a new string variable within the function scope that gets destroyed once the function call ends.
This does the trick:
VALUE = None # global variables are capitalized
def set_value(new_value):
global VALUE
VALUE = new_value
if __name__ == "__main__":
set_value("something")
print VALUE
Getter and setter functions are superfluous here, because you can always just call and set VALUE from anywhere in the script, since it’s a global variable.
And please do the community a favor and use Pythonic notation! No camel case for function names!!
PS! I don’t use if name == “main”: since I put them on buttons with -RunPythonScript () and that doesn’t like if__name__…
Any ways to work around that too?
if __name__ == "__main__" checks whether you are currently executing that Python file, meaning the one containing the if statement and only then runs the code within that statement.
This is handy, because it isn’t run when you import from the same file, instead of running it itself.
Oh cool, I didn’t realise you could run Python from inside a button, I’ve not tried that before.
Add in a simple print(__name__) you’ll see in a Button you want to test for __builtin__:
! _-RunPythonScript (
import rhinoscriptsyntax as rs
print(__name__)
if __name__ == "__builtin__":
crv_id = rs.GetObject("Select curve",rs.filter.curve,preselect=True)
print rs.CurveLength(crv_id)
)
You don’t need it anyway though, as I don’t think you can import the code in a Button anymore than you can that from a GhPython component. Neither are easily usable as modules.
However, adding in a name == main guard clause into an external module, that you import into your button could be a great idea though, e.g. for testing. But you probably need to add its path to sys.path to import it.