I am trying to set a new variable to reference a variable inside a function. My pseudo code goes like this:
def myfunction():
a bunch of stuff that results in
myvariable = "Some Text"
Further down the code I have this:
for something in somethinglist:
if something == iteminsomethinglist:
myfunction()
mynewvariable1 = myvariable
elif something == iteminsomethinglist:
myfunction()
mynewvariable2 = myvariable
else:
mynewvariable3 = myvariable
I keep getting an error message that says something like: name ‘myvariable’ is not defined
I guess I thought that if I called the function, it processes some stuff, I pass result into a variable and then reference that variable to a more unique variable, it would store it….but it’s not.
Edit: I am attaching my code because it I wasn’t clear enough in my first post. There is a variable within my function I wanted to reference outside of it (actually there are 2) I apologize for not making it clear enough. I though my original psuedo code proposed the question well enough. I also have a feeling that this might not be the best approach. Possible calling 2 functions would be more appropriate? My code is below:
def datetypedetector():
rows = arcpy.SearchCursor(fc)
dateList = []
for row in rows:
dateList.append(row.getValue("DATE_OBSERVATION").strftime('%m-%d-%Y'))
del row, rows
newList = sorted(list(set(dateList)))
dates = [datetime.strptime(d, "%m-%d-%Y") for d in newList]
date_ints = set([d.toordinal() for d in dates])
if len(date_ints) == 1:
DTYPE = "Single Date"
#print "Single Date"
elif max(date_ints) - min(date_ints) == len(date_ints) - 1:
DTYPE = "Range of Dates"
#print "Range of Dates"
else:
DTYPE = "Multiple Dates"
#print "Multiple Dates"
fcList = arcpy.ListFeatureClasses()
for fc in fcList:
if fc == "SO_SOIL_P" or fc == "AS_ECOSITE_P":
datetypedetector()
ssDate = newList
print fc + " = " + str(ssDate)
ssDatetype = DTYPE
print ssDatetype
elif fc == "VE_WEED_P":
datetypedetector()
vwDate = newList
print fc + " = " + str(vwDate)
vwDatetype = DTYPE
print vwDatetype
else:
datetypedetector()
vrDate = newList
print fc + " = " + str(vrDate)
vrDatetype = DTYPE
print vrDatetype
As written,
myvariableis only defined within the scope ofmyfunction.To make the value in that variable available outside of the function you can return it from the function:
And then use it later like this:
Edit: new information added to question.
Your indentation seems slightly off, but that may just be copy-paste trouble.
I think what you want to do is something like this:
datetypedetectorfunction takingfcas an argument.DTYPEfrom that function for later use.So first change the function signature to:
And the final statement in
datetypedetectorto:And then pass
fcas an argument when you call it, and the final step is to get theDTYPEback from the function by assigning to itdatetypedetector‘s return value.