Read Code Fast
Lesson 19 Made-up APIs
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.
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
- Line 5 Real, but with no
timeout. By defaultrequestswaits forever for an answer, so one stuck server freezes this function. - Line 6
dict.has_keywas removed in Python 3. It raises AttributeError. The real test is"stamp" in cache. - Line 8 Deprecated since Python 3.12, and it returns a datetime without a time zone. Use
datetime.now(timezone.utc). - Line 9
list.reverse()works in place and returnsNone. SonamesisNone, with no error. Usesorted(..., 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.