I suspect there are two issues with your code. Together they combine to give the exception you're seeing, but even if you could mitigate the immediately exception, the errors would still need to be fixed eventually.
The first error is a bit speculative, but I suspect that key_file[0] is an iterator (probably a csv.DictReader, or something similar). When you iterate over it the first time keys is called, it works as expected, with the items from the iterator being used as they are needed. The trouble comes the second time keys gets called, as then the iterator at that point is already exhausted, and so iterating over it doesn't do anything at all. The loop just ends immediately.
The fix for this issue is probably to dump the iterator into a sequence that you can iterate upon as many times as you want. This can be done with the equivalent of key_file[0] = list(key_file[0]) somewhere (you might be able to just put the list call in to whatever existing code assigns that value the first time around, rather than assigning the iterator first and then later converting it into a list). An alternative might be to move the whole file-opening and CSV parsing logic into keys (or into a function that keys can call) so you can recreate the iterator whenever you need it.
The other issue is that your function raises an odd exception any time you ask for the keys of a tenant that's not in your file. Now, raising some exception may be the right thing to do, but the UnboundLocalError exception you're getting now is a lot less clear than something like ValueError(f"Unknown tenant {tenant}") would be.
The most natural way to fix this second issue is probably to move the return call into the if block inside the loop, so that you immediately return the keys if you have found them. Then you can raise an appropriate exception if you make it out the end of the loop without having found anything. If you really do need to keep the logic of searching the whole file and returning the keys for the last matching line, you could initialize your fooKey values to some sentinel value like None and then check for it after the loop to see if they've changed (raising an exception they have not).
Anyway, here's my general fix:
key_file[0] = list(csv.DictReader(...)) # this is somewhere above, probably
def keys(tenant):
for line in key_file[0]:
if tenant == line.get('tenant'):
accessKey = line.get('api_key')
secretKey = line.get('secret_key')
return accessKey, secretKey # return immediately if a match is found
raise ValueError(f"Unknown tenant: {tenant}") # it's an error if you reach here
accessKeyandsecretKeywould not be assigned if the giventenantis not found in CSV file.keysis called in the second iteration.Nonefor both values by initializingaccessKeyandsecretKeyasNonefirst.