I have a python class called Video, which represents YouTube videos. Given the ID of a YouTube video, Video returns an object representing that video. However, when a Video object is first created, YouTube is not queried. YouTube is only queried once an attribute is asked for that requires information from YouTube. Here’s how it works:
>>> from video import Video
>>> video = Video('B11msns6wPU')
# 'B11msns6wPU' is the ID of a video
>>> video
Video(youtube_id="B11msns6wPU")
### As of now, no call to YouTube's API has been made
### Next, I ask for the title attribute. The object queries YouTube's API to get
### this information. In doing so, the object is completely initialized
>>> video.title
u'Badly Drawn Boy - Disillusion (directed by Garth Jennings)'
>>> video.duration
u'275'
# no query was made to the API because the object has been already been initialized
I’m not sure if this is technically “lazy evaluation”, but it is similar in flavor. Video objects aren’t initialized until the first call for an attribute is made. I’m wondering if this technique was worth implementing. Obviously, it makes my code a bit more complicated. What are your thoughts?
This is sort of a general judgement call, not a hard-and-fast decision.
If the lazy object, the
Videoclass instance, is central to your application then it might make sense to fully initialize it before doing anything else; if your app is useless without the data, get the data first.But if your app might have hundreds or thousands of these
Videoinstances, and most of them will not be used, it doesn’t make sense to make the user wait while you init them all. In this case, it would make a lot of sense to defer the initialization until it is really needed. For example, if you will be showing a “wall of thumbnails” display, you might need the thumbnail for each video and the title but you might not need anything else unless the user clicks on a thumbnail.I do like the general approach, that the code using the object doesn’t need to know or care whether the object was pre-initialized or not.