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()
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With