Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the meaning of angle brackets in Python?

I found the following lines in the scikit-learn package:

if is_sparse:
    problem = csr_set_problem(
            (<np.ndarray[np.float64_t, ndim=1, mode='c']>X.data).data,
            (<np.ndarray[np.int32_t,   ndim=1, mode='c']>X.indices).shape,
            (<np.ndarray[np.int32_t,   ndim=1, mode='c']>X.indices).data,
            (<np.ndarray[np.int32_t,   ndim=1, mode='c']>X.indptr).shape,
            (<np.ndarray[np.int32_t,   ndim=1, mode='c']>X.indptr).data,
            Y.data, (<np.int32_t>X.shape[1]), bias,
            sample_weight.data)
else:
    ...

All my searches for "angle brackets in Python" give answers about documentation or decorator syntax, which I am pretty sure this is neither because it looks like actual logic.

What do the angle brackets in the above Python code do and where can I learn more about them?

like image 610
user1717828 Avatar asked Mar 30 '17 13:03

user1717828


People also ask

What are angle brackets in Python?

Angle brackets (“<>”) have two uses. In C++, they are used in defining templates while in HTML and XML they are used to delimit tags (okay, XML purists, “tag” is not precise but its close enough). Parentheses (“()”) are normally used to define parameters of function/procedure calls.

What do angle brackets mean in code?

Angle brackets are commonly used to enclose a code of some type. For example, HTML tags and PageMaker tags are enclosed in angle brackets. They are also used on chat channels and in chat rooms to frame a comment or expression, such as <groan!> or <g>, which is short for <grin>.

What do angle brackets mean in linear algebra?

An angle bracket is the combination of a bra and ket (bra+ket = bracket) which represents the inner product of two functions or vectors (or 1-forms), in a function space, or. in a vector space.


2 Answers

That is Cython's syntax for type casting/coercion. It is not plain Python. Notice the file extension is .pyx

You can learn more about them in the documentation for Cython.

Here's an example taken from the doc page:

cdef char *p, float *q
p = <char*>q

Using Cython is not uncommon with projects like scikit-learn, where one gains significant optimisations by mixing readable Python with blazing-speed C.

like image 176
Moses Koledoye Avatar answered Sep 20 '22 14:09

Moses Koledoye


Take a look at Cython documentation, about types.

Additionally you could note that the file extension is .pyx and on the top of the file there are cimport statements.

like image 42
R Kiselev Avatar answered Sep 18 '22 14:09

R Kiselev