Simplicity
Simplicity

Reputation: 48916

What does this assignment statement mean?

I came across this Python script:

fea_det = cv2.xfeatures2d.SIFT_create()
des_ext = cv2.xfeatures2d.SIFT_create()

des_list = []

for image_path in image_paths:
    im = cv2.imread(image_path)
    kpts = fea_det.detect(im)
    kpts, des = des_ext.compute(im, kpts)
    des_list.append((image_path, des))

My issue is not related to the meaning of the different variables and parameters, but to how we can read in particular this statement:

kpts, des = des_ext.compute(im, kpts)

What would go in kpts and des? What are their data types?

Upvotes: 0

Views: 82

Answers (2)

salezica
salezica

Reputation: 76929

Python has a mechanism called unpacking. This is known in other languages as destructuring assignment.

It goes like this: when an expression evaluates to an iterable object (such as a list or tuple), you can spread the inner values to separate variables on assignment:

def get_2_tuple():
    return ('foo', 'bar')

values = get_2_tuple() # no unpacking
foo, bar = values # unpacking!

foo, bar = get_2_tuple() # same-line unpacking

The act of unpacking may raise an Exception: the function get_2_tuple() must return an iterable with exactly two values inside for it to work.

Upvotes: 0

Łukasz Rogalski
Łukasz Rogalski

Reputation: 23223

Comma separated identifiers on LHS of assignment statement performs iterable unpacking on result of RHS. Quoting docs:

If the target list is a comma-separated list of targets: The object must be an iterable with the same number of items as there are targets in the target list, and the items are assigned, from left to right, to the corresponding targets.

What are their data types?

I don't know and I don't care. Same as Python when it performs assignment. It may care if you ask these objects to do something later.

Upvotes: 1

Related Questions