Why is tuple matching in function parameters?

I was wondering why many functions - especially in numpy - use tuples as function parameters?

eg:.

a = numpy.ones( (10, 5) ) 

What could be useful for this? Why not just have something like the following, as it is clear that the first parameters will always indicate the size of the array?

 a = numpy.ones(10, 5) 

Is it because there may be additional options like dtype? even if so

 a = numpy.ones(10, 5, dtype=numpy.int) 

seems to me a lot cleaner than using a collapsed tuple.

thank you for your responses

+4
source share
4 answers

Because you want to be able to:

 a = numpy.ones(other_array.shape) 

and other_array.shape is a tuple. There are several functions that are not consistent with this and work as you described, for example. numpy.random.rand()

+3
source

I think one of the advantages of this is that it can lead to consistency between different methods. I am not familiar with numpy, but it seems to me that the first use case that comes to mind is if numpy can return the size of the array, this size as one variable can be directly passed to another numpy method, without having to know anything about internal elements of how this size element is created.

Another part of it is that the size of the array can have two components, but it is considered as one value, and not as two.

+2
source

My guess: this is because in functions like np.ones , shape can be passed as a keyword argument when it is one value. Try

 np.ones(dtype=int, shape=(2, 3)) 

and note that you get the same value that you received from np.ones((2, 3), dtype=int) .

[This works in Python in general:

 >>> def f(a, b): ... return a + b ... >>> f(b="foo", a="bar") 'barfoo' 

]

+2
source

For python to tell the difference between foo(1, 2) , foo(1, dtype='int') and foo(1, 2, dtype='int') , you would have to use arguments only for a keyword that were not formally introduced before python 3. **kargs only be used to implement key arguments in python 2.x, but this is unnatural and doesn't seem to be Pythonic. I think for this reason array does not allow array(1, 2) , but reshape(1, 2) fine, because reshape does not accept any keywords.

0
source

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


All Articles