Pages

Showing posts with label type. Show all posts
Showing posts with label type. Show all posts

Thursday, May 15, 2014

python: int and long are unified








Since Python 2.4, int and long are unified. Furthermore, from Python 3, int is the only type for integer, which has the capacity of long in Python 2.

sys.maxint returns the maximum integer number that Python can hold.

see also




python: parse boolean from string








def parse_bool(s):
    return s.lower() in ("yes", "true", "T", "1")

NOTE:

bool('foo') # True
bool('') # False
You can not use the above function to parse boolean from string.


python: check if a variable is a integer








if isinstance(var, int):
    print("It is integer")
On python 2:
if is instance(var, (int, long)):
    print("It is integer")



Friday, May 9, 2014

python: check if a variable is a string








import sys

if isinstance(var, basestring if sys.version_info[0]<3 else str):
    print("it is string") # var is string

see also




Friday, April 18, 2014

Python: check argument type








  • for objects:
    def f(arg):
        if isinstance(arg, ClassA):
            print('A')
        elif isintance(arg, ClassB):
            print('B')
        elif issubclass(arg, ClassC):
            print('subclass of C')
        else:
            print("D")
    
  • for built-in types:
    def f(arg):
        if type(arg) is str:
            print "str"
        elif type(arg) is int:
            print "int"
        elif type(arg) is dict:
            print "dict"
        else:
            print "unsupported"