how handle exception using IMDBPY

347 views Asked by At

this code works perfect with movie Id that has plot keyword .

from imdb import IMDb
ia = IMDb()
black_panther = ia.get_movie('1825683', info='keywords')
print(black_panther['keywords'])

bur for movies that haven't plot keyword like this id(5950092) it returns exception.any idea for handle exception?

2

There are 2 answers

3
Edgar Ramírez Mondragón On BEST ANSWER

Since imdb.Movie.Movie is a subclass of imdb.utils._Container with a get method similar to that of a dict, and which docstring reads:

>>> imdb.utils._Container.get.__doc__
"Return the given section, or default if it's not found."

That means you can do this to never throw an exception if there are no keywords:

movie = ia.get_movie('5950092', info='keywords')

movie.get('keywords', [])
# Result: [], empty list

You can also work with an Exception if you want to:

try:
    keywords = movie['keywords']
except KeyError:
    keywords = []
0
Davide Alberani On

In IMDbPY, Movie instances behave like dictionaries, so you handle exceptions in the usual way (with a try/except clause). See https://docs.python.org/3/tutorial/errors.html#handling-exceptions

Being dictionary-like objects, you can also test for the presence of a key with 'keywords' in black_panther and get the value without raising n exception, but returning None if the key is missing, with black_panther.get('keywords').