Pages

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




python: conditional expression









x = true_value if condition else false_value

if isinstance(s, basestring if sys.version_info[0]<3 else str):
    print('It is a str.')

see also




python: dictionary comprehension








dict = { 'a':1, 'b':2 }
dict = { k: str(dict[k]) for k in dict.keys() }
print(dict)



Thursday, May 8, 2014

main function in python module









class A:
    def __init__(self):
        pass


def main():
    print("Hello World")


if __name__ == '__main__':
    main()

see also




Tuesday, May 6, 2014

Google coding style guide for Python








Google code style for python.