开发者

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


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


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.


type(variable_name)

Then you need to use:

if type(args) is type(0):
   blabla

Above we are comparing if the type of the variable args is the same as the literal 0 which is an integer, if you wish to know if for instance the type is long, you compare with type(0l), etc.


If you know that you are expecting an integer/string argument, you shouldn't swallow it into *args. Do

def handle( self, first_arg = None, *args, **kwargs ):
    if isinstance( first_arg, int ):
        thing_one()
    elif isinstance( first_arg, str ):
        thing_two()


No one has mentioned it, but the Easier to Ask For Forgiveness principle probably applies since I presume you'll be doing something with that integer:

def handle(self, *args, **kwargs):
    try:
        #Do some integer thing
    except TypeError:
        #Do some string thing

Of course if that integer thing is modifying the values in your list, maybe you should check first. Of course if you want to loop through args and do something for integers and something else for strings:

def handle(self, *args, **kwargs):
    for arg in args:
        try:
            #Do some integer thing
        except TypeError:
            #Do some string thing

Of course this is also assuming that no other operation in the try will throw a TypeError.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜