Tumgik
dwehoziji · 5 years
Text
New Post has been published on ClintButler.net
New Post has been published on https://is.gd/gTKsMw
Python Tricks: "for" (and "while") loops can have an "else" branch?!
# Python's `for` and `while` loops # support an `else` clause that executes # only if the loops terminates without # hitting a `break` statement. def contains(haystack, needle): """ Throw a ValueError if `needle` not in `haystack`. """ for item in haystack: if item == needle: break else: # The `else` here is a # "completion clause" that runs # only if the loop ran to completion # without hitting a `break` statement. raise ValueError('Needle not found') >>> contains([23, 'needle', 0xbadc0ffee], 'needle') None >>> contains([23, 42, 0xbadc0ffee], 'needle') ValueError: "Needle not found" # Personally, I'm not a fan of the `else` # "completion clause" in loops because # I find it confusing. I'd rather do # something like this: def better_contains(haystack, needle): for item in haystack: if item == needle: return raise ValueError('Needle not found') # Note: Typically you'd write something # like this to do a membership test, # which is much more Pythonic: if needle not in haystack: raise ValueError('Needle not found')
0 notes
dwehoziji · 6 years
Text
New Post has been published on ClintButler.net
New Post has been published on https://is.gd/eUrSXp
Python Tricks: Python 3.3+ has a new "faulthandler" std lib module
# Python 3.3+ has a std # lib module for displaying # tracebacks even when Python # "dies", e.g with a segfault: import faulthandler faulthandler.enable() # Can also be enabled with # "python -X faulthandler" # from the command line. # Learn more here: # https://docs.python.org/3/library/faulthandler.html
0 notes
dwehoziji · 6 years
Text
New Post has been published on ClintButler.net
New Post has been published on https://is.gd/8iM3ZP
Python Tricks: Python's namedtuples can be a great alternative to defining a class manually
# Why Python is Great: Namedtuples # Using namedtuple is way shorter than # defining a class manually: >>> from collections import namedtuple >>> Car = namedtuple('Car', 'color mileage') # Our new "Car" class works as expected: >>> my_car = Car('red', 3812.4) >>> my_car.color 'red' >>> my_car.mileage 3812.4 # We get a nice string repr for free: >>> my_car Car(color='red' , mileage=3812.4) # Like tuples, namedtuples are immutable: >>> my_car.color = 'blue' AttributeError: "can't set attribute"
0 notes
dwehoziji · 6 years
Text
New Post has been published on ClintButler.net
New Post has been published on https://is.gd/2ZftYe
Python Tricks: You can use "json.dumps()" to pretty-print Python dicts
# The standard string repr for dicts is hard to read: >>> my_mapping = 'a': 23, 'b': 42, 'c': 0xc0ffee >>> my_mapping 'b': 42, 'c': 12648430. 'a': 23 # 😞 # The "json" module can do a much better job: >>> import json >>> print(json.dumps(my_mapping, indent=4, sort_keys=True)) "a": 23, "b": 42, "c": 12648430 # Note this only works with dicts containing # primitive types (check out the "pprint" module): >>> json.dumps(all: 'yup') TypeError: keys must be a string
0 notes
dwehoziji · 6 years
Text
New Post has been published on ClintButler.net
New Post has been published on https://is.gd/a6AnUr
Python Tricks: Function argument unpacking in Python
# Why Python Is Great: # Function argument unpacking def myfunc(x, y, z): print(x, y, z) tuple_vec = (1, 0, 1) dict_vec = 'x': 1, 'y': 0, 'z': 1 >>> myfunc(*tuple_vec) 1, 0, 1 >>> myfunc(**dict_vec) 1, 0, 1
0 notes
dwehoziji · 6 years
Text
New Post has been published on ClintButler.net
New Post has been published on https://is.gd/Q3xfh1
Python Tricks: Measure the execution time of small bits of Python code with the "timeit" module
# The "timeit" module lets you measure the execution # time of small bits of Python code >>> import timeit >>> timeit.timeit('"-".join(str(n) for n in range(100))', number=10000) 0.3412662749997253 >>> timeit.timeit('"-".join([str(n) for n in range(100)])', number=10000) 0.2996307989997149 >>> timeit.timeit('"-".join(map(str, range(100)))', number=10000) 0.24581470699922647
0 notes
dwehoziji · 6 years
Text
New Post has been published on ClintButler.net
New Post has been published on https://is.gd/YO88K6
Python Tricks: Python's shorthand for in-place value swapping
# Why Python Is Great: # In-place value swapping # Let's say we want to swap # the values of a and b... a = 23 b = 42 # The "classic" way to do it # with a temporary variable: tmp = a a = b b = tmp # Python also lets us # use this short-hand: a, b = b, a
0 notes
dwehoziji · 6 years
Text
New Post has been published on ClintButler.net
New Post has been published on https://is.gd/vX5rqY
Python Tricks: "is" vs "=="
# "is" vs "==" >>> a = [1, 2, 3] >>> b = a >>> a is b True >>> a == b True >>> c = list(a) >>> a == c True >>> a is c False # • "is" expressions evaluate to True if two # variables point to the same object # • "==" evaluates to True if the objects # referred to by the variables are equal
0 notes
dwehoziji · 6 years
Text
New Post has been published on ClintButler.net
New Post has been published on https://is.gd/Ws594p
Python Tricks: Functions are first-class citizens in Python
# Functions are first-class citizens in Python: # They can be passed as arguments to other functions, # returned as values from other functions, and # assigned to variables and stored in data structures. >>> def myfunc(a, b): ... return a + b ... >>> funcs = [myfunc] >>> funcs[0] <function myfunc at 0x107012230> >>> funcs[0](2, 3) 5
0 notes
dwehoziji · 6 years
Text
New Post has been published on ClintButler.net
New Post has been published on https://is.gd/WNmslK
Python Tricks: Python list slice syntax fun
# Python's list slice syntax can be used without indices # for a few fun and useful things: # You can clear all elements from a list: >>> lst = [1, 2, 3, 4, 5] >>> del lst[:] >>> lst [] # You can replace all elements of a list # without creating a new list object: >>> a = lst >>> lst[:] = [7, 8, 9] >>> lst [7, 8, 9] >>> a [7, 8, 9] >>> a is lst True # You can also create a (shallow) copy of a list: >>> b = lst[:] >>> b [7, 8, 9] >>> b is lst False
0 notes
dwehoziji · 6 years
Text
New Post has been published on ClintButler.net
New Post has been published on https://is.gd/fUPNk9
Python Tricks: CPython easter egg
# Here's a fun little CPython easter egg. # Just run the following in a Python 2.7+ # interpreter session: >>> import antigravity
0 notes
dwehoziji · 6 years
Text
New Post has been published on ClintButler.net
New Post has been published on https://is.gd/s050Q7
Python Tricks: Finding the most common elements in an iterable
# collections.Counter lets you find the most common # elements in an iterable: >>> import collections >>> c = collections.Counter('helloworld') >>> c Counter('l': 3, 'o': 2, 'e': 1, 'd': 1, 'h': 1, 'r': 1, 'w': 1) >>> c.most_common(3) [('l', 3), ('o', 2), ('e', 1)]
0 notes
dwehoziji · 6 years
Text
New Post has been published on ClintButler.net
New Post has been published on https://is.gd/goxrJW
Python Tricks: itertools.permutations()
# itertools.permutations() generates permutations # for an iterable. Time to brute-force those passwords ;-) >>> import itertools >>> for p in itertools.permutations('ABCD'): ... print(p) ('A', 'B', 'C', 'D') ('A', 'B', 'D', 'C') ('A', 'C', 'B', 'D') ('A', 'C', 'D', 'B') ('A', 'D', 'B', 'C') ('A', 'D', 'C', 'B') ('B', 'A', 'C', 'D') ('B', 'A', 'D', 'C') ('B', 'C', 'A', 'D') ('B', 'C', 'D', 'A') ('B', 'D', 'A', 'C') ('B', 'D', 'C', 'A') ('C', 'A', 'B', 'D') ('C', 'A', 'D', 'B') ('C', 'B', 'A', 'D') ('C', 'B', 'D', 'A') ('C', 'D', 'A', 'B') ('C', 'D', 'B', 'A') ('D', 'A', 'B', 'C') ('D', 'A', 'C', 'B') ('D', 'B', 'A', 'C') ('D', 'B', 'C', 'A') ('D', 'C', 'A', 'B') ('D', 'C', 'B', 'A')
0 notes
dwehoziji · 6 years
Text
New Post has been published on ClintButler.net
New Post has been published on https://is.gd/eEgfwJ
Python Tricks: @classmethod vs @staticmethod vs "plain" methods
# @classmethod vs @staticmethod vs "plain" methods # What's the difference? class MyClass: def method(self): """ Instance methods need a class instance and can access the instance through `self`. """ return 'instance method called', self @classmethod def classmethod(cls): """ Class methods don't need a class instance. They can't access the instance (self) but they have access to the class itself via `cls`. """ return 'class method called', cls @staticmethod def staticmethod(): """ Static methods don't have access to `cls` or `self`. They work like regular functions but belong to the class's namespace. """ return 'static method called' # All methods types can be # called on a class instance: >>> obj = MyClass() >>> obj.method() ('instance method called', <MyClass instance at 0x1019381b8>) >>> obj.classmethod() ('class method called', <class MyClass at 0x101a2f4c8>) >>> obj.staticmethod() 'static method called' # Calling instance methods fails # if we only have the class object: >>> MyClass.classmethod() ('class method called', <class MyClass at 0x101a2f4c8>) >>> MyClass.staticmethod() 'static method called' >>> MyClass.method() TypeError: "unbound method method() must be called with MyClass " "instance as first argument (got nothing instead)"
0 notes
dwehoziji · 6 years
Text
New Post has been published on ClintButler.net
New Post has been published on https://is.gd/opWggB
Python Tricks: : Accessing class and function names at runtime
# You can get the name of # an object's class as a # string: >>> class MyClass: pass >>> obj = MyClass() >>> obj.__class__.__name__ 'MyClass' # Functions have a # similar feature: >>> def myfunc(): pass >>> myfunc.__name__ 'myfunc'
0 notes
dwehoziji · 6 years
Text
New Post has been published on ClintButler.net
New Post has been published on https://is.gd/KOsUqp
Python Tricks: Dicts can be used to emulate switch/case statements
# Because Python has first-class functions they can # be used to emulate switch/case statements def dispatch_if(operator, x, y): if operator == 'add': return x + y elif operator == 'sub': return x - y elif operator == 'mul': return x * y elif operator == 'div': return x / y else: return None def dispatch_dict(operator, x, y): return 'add': lambda: x + y, 'sub': lambda: x - y, 'mul': lambda: x * y, 'div': lambda: x / y, .get(operator, lambda: None)() >>> dispatch_if('mul', 2, 8) 16 >>> dispatch_dict('mul', 2, 8) 16 >>> dispatch_if('unknown', 2, 8) None >>> dispatch_dict('unknown', 2, 8) None
0 notes
dwehoziji · 6 years
Text
New Post has been published on ClintButler.net
New Post has been published on https://is.gd/JVvhau
Python Tricks: Python's built-in HTTP server
# Python has a HTTP server built into the # standard library. This is super handy for # previewing websites. # Python 3.x $ python3 -m http.server # Python 2.x $ python -m SimpleHTTPServer 8000 # (This will serve the current directory at # http://localhost:8000)
0 notes