The difference between __str__ and __repr__ in Python

Both turn an object into a string. __str__ is for people, __repr__ is for you when something has gone wrong — and if you only ever define one of them, define __repr__.

The difference between @staticmethod and @classmethod in Python

The mechanical difference is one line: a classmethod receives the class, a staticmethod receives nothing. Why that matters only becomes visible when somebody subclasses your class, which is where this article spends its time.

What if __name__ == "__main__": does in Python

You find these two lines at the bottom of a great many Python files. This article explains what they do, why they are worth writing, and one consequence of getting the entry point wrong that is very hard to debug if you have not met it before.

What metaclasses are in Python

A metaclass is the class of a class. That sentence is correct and completely useless on its own, so this article builds up to it, shows when each hook actually fires, and then argues that you probably want something simpler.

What the yield keyword does in Python

Python is a high level programming language with a large standard library. In this article you will learn what the yield keyword does, why a function that contains it behaves so differently from a normal one, and where the memory savings people talk about actually come from.

PHP: How do you calculate the days between two dates?

The answer is one line. What is interesting is the other, older solution you find at least as often: the difference of the timestamps, divided by 86400. That one is wrong twice a year, and no amount of rounding fixes it.

PHP: How do you check whether a string starts or ends with something?

You often face the requirement of determining whether a string starts or ends with a particular substring. For example whether a URL starts with https://, or whether a file name ends in .php.

PHP: How do you check whether an array is a list or associative?

PHP has only one array type, which serves as both a list and a dictionary. Sometimes you need to know which of the two you are holding — and by the time you get to JSON it definitely matters.

PHP: How do you convert a string to a number?

There is a cast for the conversion, and it works. The real question is usually a different one though: what should happen when the string is not a number at all? The cast answers that silently, and rarely in a way you can use.

PHP: How do you convert an object into an array?

The cast (array) $object is the answer you find everywhere. With a stdClass it does work. With a class of your own it gives you keys you can no longer address.