bluevoxel
bluevoxel

Reputation: 5358

How do I know what type my variable is?

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.

Upvotes: 2

Views: 495

Answers (5)

Lee
Lee

Reputation: 31040

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

Upvotes: 2

ch3ka
ch3ka

Reputation: 12158

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

>>> help(x)

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

Upvotes: 0

generalpiston
generalpiston

Reputation: 891

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.

Upvotes: 2

dmitry_romanov
dmitry_romanov

Reputation: 5425

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

Upvotes: 1

Ffisegydd
Ffisegydd

Reputation: 53668

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')

Upvotes: 3

Related Questions