-1

This code does not seem to work:

class Dog:
    def __init__(self,color):
        assert type(color) == 'str', 'Must be string'
        self.color = color

dog = Dog('black')


line 26, in __init__ assert type(color) == 'str', 'Must be string'
AssertionError: Must be string

Even though I've used a string. Is their a way to check if a given argument has the correct type?

Minuet
  • 83
  • 7
  • 1
    `type(color) == str`, not `type(color) == 'str'`. Also, check [`isinstance`](https://docs.python.org/3/library/functions.html#isinstance) out. – ytu Dec 07 '19 at 16:50
  • 1
    Does this answer your question? [Determine the type of an object?](https://stackoverflow.com/questions/2225038/determine-the-type-of-an-object) – ytu Dec 07 '19 at 16:52
  • I feel it is important to mention that this is probably unidiomatic. Also, `assert` should really only be used for debugging. – AMC Dec 07 '19 at 21:50

2 Answers2

2

First, 'str' and str are different: the first one is a string, and the second one is the str class. If you compare with the class, (type('hello') == str) is True.

You most likely want to check if the argument is an instance of str:

assert isinstance(color, str), 'Must be string'
ForceBru
  • 43,482
  • 10
  • 63
  • 98
1

If you want to check types, without using isinstance, this is your alternative.

assert type(color) == type(""), 'Must be string'

or

assert type(color) == str, 'Must be string'
Pratik
  • 1,351
  • 1
  • 20
  • 37
  • why not just `type(color) == str`? – Tomerikoo Dec 07 '19 at 16:53
  • @Tomerikoo correct, editing my answer – Pratik Dec 07 '19 at 16:54
  • @Tomerikoo `type()`and `isinstance()`are not the same thing. (https://stackoverflow.com/q/1549801/11301900) – AMC Dec 07 '19 at 17:40
  • @AlexanderCécile I am well aware of that. My point was: considering the code present is `type(color) == type("")`, you might as well write `type(color) == str`. Whether that is the correct approach or not, I didn't claim to state. Simply an obvious fix – Tomerikoo Dec 07 '19 at 18:43
  • @Tomerikoo My apologies, somehow I thought you were the author of this answer. – AMC Dec 07 '19 at 18:47