0

I am attempting to create a list of video objects, which have a name attribute which is set on initiation and then other attrs. that are loaded from ffprobe call fetching metadata. The ffmpeg calls are obviously slower to run, so I have written the class as follows:

class Video:

    def __init__(self, path, name):
        self.name = name
        self.path = path

    def get_length(self):
        if self.length:
            return self.length
        else:
            self.length = slow_function()
        return self.length

This way I can just fetch the attribute at a point of time where I need to reference the attr and the value is "set" on the "get" call.

Is this the proper way to do this? Is there a better way?

Thanks.

1 Answer 1

3

Slightly cleaner would be to initialize self.length to None, then call the slow function if self.length is still None.

class Video:

    def __init__(self, path, name):
        self.name = name
        self.path = path
        self.length = None

    def get_length(self):
        if self.length is None:
            self.length = slow_function()

        return self.length

Such lazily defined attributes are usually implemented with a property.

class Video:

    def __init__(self, path, name):
        self.name = name
        self.path = path
        self._length = None

    @property
    def length(self):
        if self._length is None:
            self._length = slow_function()

        return self._length

Now you can access length as what appears to be a regular (though read-only) attribute

v = Video(...)
print(v.length)

rather than an explicit method call.

Sign up to request clarification or add additional context in comments.

1 Comment

ooh interesting, learnt something new here. I guess there is a special decorator for property functions aye. Thanks for the tip!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.