Blue
Blue

Reputation: 169

Why isn't the type() function working here?

I am learning Python, and I was trying to see if functions behave as I expected them to. However, I ran across an issue:

import numpy as np

def test():
     return np.array([1, 2, 3])

type(test())

I would expect the output to be numpy.ndarray. However, I get nothing when I run this script.

I have tried different things instead of the type function; for example, print(test()) worked as expected. But for some reason the type function doesn't seem to work. Could you please enlightment me as to why? Thanks!

Upvotes: 1

Views: 829

Answers (2)

Petru Tanas
Petru Tanas

Reputation: 1237

A couple of things:

  1. You have to print the output

  2. There are 2 different cases:

import numpy as np

def test():
     return np.array([1, 2, 3])

print(type(test))
print(type(test()))

first will print "class 'function'" the actual type of test

second (your case) will actually call the function (because you wrote it wih (), so test() ) and thus the return will be evaluated, and type will return the type of the result, which will be here "class 'numpy.ndarray'"

Upvotes: 2

Riley
Riley

Reputation: 189

You need to print the output of test to be able to see it. Try this:

import numpy as np

def test():
     return np.array([1, 2, 3])

print(type(test()))

Edit: In Python's interactive console, you don't need to print things to be able to see their output, so that may have tripped you up a bit :|

Upvotes: 3

Related Questions