2

I don't know how to determine type of a given variable while I read Python code. I would like to know the types of variables without the deep knowledge of methods that initialize values for them. Say, I have piece of code:

import numpy as np np.random.seed(0) n = 10000 x = np.random.standard_normal(n) y = 2.0 + 3.0 * x + 4.0 * np.random.standard_normal(n) xmin = x.min() xmax = x.max() ymin = y.min() ymax = y.max() 

How do I know what type x is? In Java it's simple. Even if I don't know the method, I know the variable type.

5 Answers 5

3

You can use the builtin type function to check the type of a variable.

import numpy as np np.random.seed(0) n = 10000 x = np.random.standard_normal(n) print(type(x)) # numpy.ndarray 

If, in the specific case of numpy, you want to check the type of your elements, then you can do

print(x.dtype) # dtype('float64') 
Sign up to request clarification or add additional context in comments.

Comments

2

Python is a dynamically typed language. Technically, when reading code, you won't be able to know the type of a variable without following the code, or if the code is excessively simple.

A few quotes for you:

Python is strongly typed as the interpreter keeps track of all variables types. It's also very dynamic as it rarely uses what it knows to limit variable usage.

In Python, it's the program's responsibility to use built-in functions like isinstance() and issubclass() to test variable types and correct usage.

You can use isinstance(x, type) or type(x) to learn about the variables type information at runtime.

Comments

2

Use dtype:

n = 10000 x = np.random.standard_normal(n) x.dtype 

gives:

dtype('float64') 

If you want more detailed information on the array attributes, you could use info:

np.info(x) 

gives:

class: ndarray shape: (10000,) strides: (8,) itemsize: 8 aligned: True contiguous: True fortran: True data pointer: 0xba10c48 byteorder: little byteswap: False type: float64 

Comments

1

type(x) is straitforward answer. Normally you don't test type it through type but use isinstance(x, type) to test it.

Comments

0

in the REPL (interactive console), you can also do

>>> help(x) 

and it will display information about x's class, including it's methods.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.