Why is “1000000000000000 in range(1000000000000001)” so fast in Python 3?

The Python 3 range() object doesn’t produce numbers immediately; it is a smart sequence object that produces numbers on demand. All it contains is your start, stop and step values, then as you iterate over the object the next integer is calculated each iteration. The object also implements the object.__contains__ hook, and calculates if your … Read more

Convert string “Jun 1 2005 1:33PM” into datetime

datetime.strptime parses an input string in the user-specified format into a timezone-naive datetime object: >>> from datetime import datetime >>> datetime.strptime(‘Jun 1 2005 1:33PM’, ‘%b %d %Y %I:%M%p’) datetime.datetime(2005, 6, 1, 13, 33) To obtain a date object using an existing datetime object, convert it using .date(): >>> datetime.strptime(‘Jun 1 2005’, ‘%b %d %Y’).date() date(2005, … Read more

How do I access environment variables in Python?

Environment variables are accessed through os.environ: import os print(os.environ[‘HOME’]) To see a list of all environment variables: print(os.environ) If a key is not present, attempting to access it will raise a KeyError. To avoid this: # Returns `None` if key doesn’t exist print(os.environ.get(‘KEY_THAT_MIGHT_EXIST’)) # Returns `default_value` if key doesn’t exist print(os.environ.get(‘KEY_THAT_MIGHT_EXIST’, default_value)) # Returns `default_value` … Read more

How do I print colored text to the terminal?

This somewhat depends on what platform you are on. The most common way to do this is by printing ANSI escape sequences. For a simple example, here’s some Python code from the Blender build scripts: class bcolors: HEADER = ‘\033[95m’ OKBLUE = ‘\033[94m’ OKCYAN = ‘\033[96m’ OKGREEN = ‘\033[92m’ WARNING = ‘\033[93m’ FAIL = ‘\033[91m’ … Read more

How do I split a list into equally-sized chunks?

Here’s a generator that yields evenly-sized chunks: def chunks(lst, n): “””Yield successive n-sized chunks from lst.””” for i in range(0, len(lst), n): yield lst[i:i + n] import pprint pprint.pprint(list(chunks(range(10, 75), 10))) [[10, 11, 12, 13, 14, 15, 16, 17, 18, 19], [20, 21, 22, 23, 24, 25, 26, 27, 28, 29], [30, 31, 32, 33, … Read more

Manually raising (throwing) an exception in Python

How do I manually throw/raise an exception in Python? Use the most specific Exception constructor that semantically fits your issue. Be specific in your message, e.g.: raise ValueError(‘A very specific bad thing happened.’) Don’t raise generic exceptions Avoid raising a generic Exception. To catch it, you’ll have to catch all other more specific exceptions that … Read more

Understanding Python super() with __init__() methods [duplicate]

super() lets you avoid referring to the base class explicitly, which can be nice. But the main advantage comes with multiple inheritance, where all sorts of fun stuff can happen. See the standard docs on super if you haven’t already. Note that the syntax changed in Python 3.0: you can just say super().__init__() instead of … Read more

How do I make function decorators and chain them together?

If you are not into long explanations, see Paolo Bergantino’s answer. Decorator Basics Python’s functions are objects To understand decorators, you must first understand that functions are objects in Python. This has important consequences. Let’s see why with a simple example : def shout(word=”yes”): return word.capitalize()+”!” print(shout()) # outputs : ‘Yes!’ # As an object, … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)