Have you ever switched between JavaScript and Python, wrote some "perfectly fine" code, and got hit with an error like:
TypeError: 'AIMessage' object is not subscriptable
I did. And I was simply trying to access .content from a LangChain AIMessage response. Here's what happened and why it matters if you're thinking in JavaScript while writing Python.
β The JavaScript Way
In JavaScript, objects are flexible:
const person = { name: "Asim" };
console.log(person.name); // β
"Asim"
console.log(person["name"]); // β
"Asim"
Both dot notation and bracket notation work. You can use either depending on the context (e.g., dynamic keys with brackets).
π The Python Way
In Python, it depends on the type:
# Dictionary (like JS object)
person = { "name": "Asim" }
print(person["name"]) # β
Works
print(person.name) # β AttributeError
# Object / Class instance
class Person:
def __init__(self, name):
self.name = name
p = Person("Asim")
print(p.name) # β
Works
print(p["name"]) # β TypeError
So when I wrote this in Python:
print(state["messages"][-1]["content"]) # β TypeError
β¦it failed because state["messages"][-1] was not a dictionary. It was a LangChain AIMessage object. The fix?
print(state["messages"][-1].content) # β
π‘ TL;DR
| Language | Dot Notation | Bracket Notation | Notes |
|---|---|---|---|
| JavaScript | β
obj.key
|
β
obj["key"]
|
Interchangeable |
| Python Dict | β dict.key
|
β
dict["key"]
|
Dot works only for objects |
| Python Obj | β
obj.prop
|
β obj["prop"]
|
Brackets work only for dicts |
π§ Final Thoughts
If you're coming from JavaScript and working in Python (especially with tools like LangChain), remember:
Not everything is a dictionary. And not everything can be accessed with brackets.
This subtle difference can cost hours of debugging if youβre in the zone and writing fast.
Have you faced a similar gotcha when switching languages? Let me know below π
Top comments (0)