Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type checking of arguments Python [duplicate]

Sometimes checking of arguments in Python is necessary. e.g. I have a function which accepts either the address of other node in the network as the raw string address or class Node which encapsulates the other node's information.

I use type() function as in:

    if type(n) == type(Node):         do this     elif type(n) == type(str)         do this 

Is this a good way to do this?

Update 1: Python 3 has annotation for function parameters. These can be used for type checks using tool: http://mypy-lang.org/

like image 444
Xolve Avatar asked Apr 09 '09 13:04

Xolve


People also ask

What are the 4 types of arguments in Python?

5 Types of Arguments in Python Function Definition:positional arguments. arbitrary positional arguments. arbitrary keyword arguments.

What are the 3 types of arguments in Python?

Hence, we conclude that Python Function Arguments and its three types of arguments to functions. These are- default, keyword, and arbitrary arguments.

How do you check if an object is a certain type in Python?

Python isinstance() Function The isinstance() function returns True if the specified object is of the specified type, otherwise False . If the type parameter is a tuple, this function will return True if the object is one of the types in the tuple.

What is type () in Python?

Python type() is a built-in function that returns the type of the objects/data elements stored in any data type or returns a new type object depending on the arguments passed to the function. The Python type() function prints what type of data structures are used to store the data elements in a program.


Video Answer


1 Answers

Use isinstance(). Sample:

if isinstance(n, unicode):     # do this elif isinstance(n, Node):     # do that ... 
like image 171
Johannes Weiss Avatar answered Oct 04 '22 16:10

Johannes Weiss