Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check type of variable? Python

I need to do one thing if args is integer and ather thing if args is string.

How can i chack type? Example:

def handle(self, *args, **options):

        if not args:
           do_something()
        elif args is integer:
           do_some_ather_thing:
        elif args is string: 
           do_totally_different_thing()
like image 804
Pol Avatar asked Aug 09 '10 14:08

Pol


People also ask

How do you check if a variable is a type?

Using the typeof Operator The typeof operator is used to check the variable type in JavaScript. It returns the type of variable. We will compare the returned value with the “boolean” string, and if it matches, we can say that the variable type is Boolean.

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.


2 Answers

First of, *args is always a list. You want to check if its content are strings?

import types
def handle(self, *args, **options):
    if not args:
       do_something()
    # check if everything in args is a Int
    elif all( isinstance(s, types.IntType) for s in args):
       do_some_ather_thing()
    # as before with strings
    elif all( isinstance(s, types.StringTypes) for s in args):
       do_totally_different_thing()

It uses types.StringTypes because Python actually has two kinds of strings: unicode and bytestrings - this way both work.

In Python3 the builtin types have been removed from the types lib and there is only one string type. This means that the type checks look like isinstance(s, int) and isinstance(s, str).

like image 172
Jochen Ritzel Avatar answered Oct 04 '22 13:10

Jochen Ritzel


You could also try to do it in a more Pythonic way without using type or isinstance(preferred because it supports inheritance):

if not args:
     do_something()
else:
     try:
        do_some_other_thing()
     except TypeError:
        do_totally_different_thing()

It obviously depends on what do_some_other_thing() does.

like image 37
systempuntoout Avatar answered Oct 04 '22 14:10

systempuntoout