Read Code Fast

Lesson 19 Made-up APIs

6 min read · Python · Quiz

invented methods and options, wrong library versions

What you'll learn

  • Spot methods and options that sound real but do not exist
  • Check an unfamiliar call in ten seconds with a REPL
  • Notice calls that run but return something else than assumed

AI assistants write method names that sound right. Some of them have never existed in Python, and some only worked in Python 2.

The idea

An AI predicts the next likely word, so it can write list.push, str.contains or dict.has_key: they come from JavaScript or old Python. Other calls are real but changed, such as datetime.utcnow(), now deprecated. And some are real and used wrongly: the call runs and the result is not what the code assumes.

You can check an unfamiliar name in ten seconds. Look for the editor underline, or paste the call into the python prompt and run it on a tiny value. A one-line test beats the docs from memory. Do this for every method you don't know by heart.

refresh_prices.py
1import requests2from datetime import datetime34def refresh_prices(skus, cache):5    resp = requests.get(PRICE_URL, params={"skus": ",".join(skus)})6    if cache.has_key("stamp"):7        del cache["stamp"]8    cache["stamp"] = datetime.utcnow()9    names = sorted(resp.json()).reverse()10    return names
  1. Line 5 Real, but with no timeout. By default requests waits forever for an answer, so one stuck server freezes this function.
  2. Line 6 dict.has_key was removed in Python 3. It raises AttributeError. The real test is "stamp" in cache.
  3. Line 8 Deprecated since Python 3.12, and it returns a datetime without a time zone. Use datetime.now(timezone.utc).
  4. Line 9 list.reverse() works in place and returns None. So names is None, with no error. Use sorted(..., reverse=True).

Take away

  • A method that sounds right is not proof it exists. Check it at the python prompt.
  • Some calls are from Python 2, from JavaScript, or deprecated in your version.
  • A call that runs can still return something else than the code assumes.

Quiz: test yourself

7 questions: a quick quiz, then a review drill. Pick an answer to see why it's right.