Select to view content in your preferred language

PYT: arcpy.mp.ArcGISProject("CURRENT") doesn't work on toolbox initialization?

105
2
a month ago
AlfredBaldenweck
MVP Regular Contributor

I'm trying to set a global variable containing the current APRX version.

glblcurVer = arcpy.mp.ArcGISProject("CURRENT").documentVersion

This works great for the most part except it gives me an OS error if I call this as part of the toolbox initialization.

AlfredBaldenweck_0-1732727928191.png

Does anyone have any ideas for how to make this work? It's a variable used in a majority of the tools in this toolbox, so I'd prefer to not have to re-create it for each tool.

EDIT: My temporary work around is to call a function to set the global variable on each tool's initialization, rather than on the PYT. It appears to work so far, but I'm still open to ideas, here.

0 Kudos
2 Replies
GISDepartmentMFM
Emerging Contributor

I have found it to be kind of dangerous to work with global variables in toolboxes because weird errors like this can happen. especially with the current workspace. what I have ended up doing as my standard is create a variable that contains that current path in execution step and just pass that into all my functions. there are probably better ways of doing things but it has stopped errors related to environment from occurring so I'm happy.

AlfredBaldenweck
MVP Regular Contributor

Yeah, what I did was like

globalvar1 = ""
globalvar2 = ""

def setglobals():
    code
    global globalvar1
    global globalvar2
    code 
    return 

class Tool:
    def __init__(self):
        """Define the tool (tool name is the name of the class)."""
        self.label = "Tool"
        self.description = ""
        setglobals()

 

It didn't work if I called setglobals() during the pyt initialization, but instead I just call it during each tool's initialization and it's worked so far.

0 Kudos