Well, I have a json file that I load in a variable and if the file doesn’t exist, I make a dictionary that will soon become the json file. So good, I’m trying to look for specific elements of this dictionary and that’s why I’m using generator expressions.
This is how I use it:
Data = json.load(open(file)) if isfile("data.json") else {"News": {},"Records": {},"Profiles": []}
name = "asdadsefttytryrty"
get = next(get for get in Data["Profiles"] if get["Name"] == name or get["ID"] == name)
and the dictionary data
would be something like this:
{
"News": {},
"Records": {},
"Profiles": [
{
"Name": "123rd453",
"ID": "1",
"Password": "dfsdfee",
"Image": "image"
},
{
"Name": "asdadsefttytryrty",
"ID": "2",
"Password": "12345",
"Image": "image"
}
]
}
So okay, this has a problem if the element I’m looking for doesn’t exist: StopIteration
So to check that the element exists, I wanted to do an if-else to perform certain operations, but I couldn’t. So I decided to use try-except as a temporary solution and I don’t think it’s reliable.
Data = json.load(open(file)) if isfile("data.json") else {"News": {},"Records": {},"Profiles": []}
name = "asdadsefttytryrty"
try:
get = next(get for get in Data["Profiles"] if get["Name"] == name or get["ID"] == name)
print("exist")
except:
print("Doesn't exist")
Doing this is correct?
2
Answers
Don’t make things complicated. You can simply do this:
Use the
path.exists()
method fromos
module to check if a certain path exists.Declaring variables at the start is a good practice.
next
does raiseStopIteration
when the given iterator is exhausted, so what you’re doing is basically correct and reliable, with the only thing to add being the specific exception you’re expecting, in order not to catch unexpected exceptions such asKeyboardInterrupt
:That said, in this case the code would arguably be cleaner and more readable written with a
for-else
construct instead: