I don't like Python functions that take two or more iterations. Is that a good idea?

This question arose from the consideration of this question :

def fringe8((px, py), (x1, y1, x2, y2)): 

Personally, I was one of my pets to see a function that takes two arguments with iterations with a fixed number (like a tuple) or two or more dictionaries (like in the shotgun API ). It is simply difficult to use because of all the verbose and two-line cabinets.

Isn't it better:

 >>> class Point(object): ... def __init__(self, x, y): ... self.x = x ... self.y = y ... >>> class Rect(object): ... def __init__(self, x1, y1, x2, y2): ... self.x1 = x1 ... self.y1 = y1 ... self.x2 = x2 ... self.y2 = y2 ... >>> def fringe8(point, rect): ... # ... ... >>> >>> point = Point(2, 2) >>> rect = Rect(1, 1, 3, 3) >>> >>> fringe8(point, rect) 

Is there a situation where it is justified to take two or more iterative arguments? Obviously, this standard itertools Python library needs this, but I don't see it to be perfect in the supported flexible code.

+3
source share
2 answers

Unpack def syntax like

 def fringe8((px, py), (x1, y1, x2, y2)): 

left in Python 3 - this means that Guido considered it a design error, or at least an unreasonable complication. Named tuples can even be better than special classes for the refinement goal that you propose.

However, having functions that take multiple iterative arguments is just fine - itertools obviously cannot encapsulate every multitasking manipulation your applications may need! Thinking that it is feasible as a β€œthread” (possibly unlimited), there are a huge number of ways in which you might want to β€œmerge” several threads into one, for example (for example, think of threads that are known to be sorted and you may need to build an intersection or union with or without duplicate removal, etc.).

Why would you ever need to combine one API design in order to obey a completely arbitrary prohibition on having no more than one iterability for each function signature ?!

+7
source

I agree with you that people tend to overuse lists and dictionaries as data structures just because they can. They see it as a simple way of grouping as data that does not require any work to define a class or work with constructors. However, when you start to do more tasks with this data, you will find it difficult to recover which part of the data was 2nd on the list and which was 5th. Creating a class allows you to more clearly define things and allows you to separate functions that directly work with your data structure.

As long as you think of it as a lot of iterations, I don't see a problem in it. Some features do require multiple lists (see Built-in zip ). But I think that the example you cited is a case where tuples are used, because it seems simpler, but it may not be so clear.

+1
source

Source: https://habr.com/ru/post/1309844/


All Articles