Explain Codes LogoExplain Codes Logo

Typeerror: 'int' object does not support indexing

python
typeerror
parameter-passing
sql-query
Anton ShumikhinbyAnton ShumikhinΒ·Nov 29, 2024
⚑TLDR

This TypeError sneaks in when you dare to use indexing (e.g., var[0]) on an integer in Python, a currency in the world of SQL query results. Verify non-indexable types like integers are not being challenged for indexing. When extracting a lone ranger from a SQL query, make sure not to treat it as a family:

Typical usage for a single integer result:

# SQL reporting: Here's your result, boss πŸ“Š result = cursor.execute("SELECT COUNT(*) FROM table").fetchone() print(result) # No need to peek and poke

For a result set doling out a tuple with a solitary integer, give it space:

# SQL reporting: We come as a pair, but hey, only one that counts! πŸ‘―β€β™€οΈ count, = cursor.execute("SELECT COUNT(*) FROM table").fetchone() print(count) # Show the singleton some print time

Driver's guide to SQL query parameter passing

When having a ball with databases via Python's DB-API, a source of gael-force TypeError often lies in disorderly parameter passing.

Nailing the placeholders

Salute to %s or ? as placeholders, and pass parameters wrapped in the comforts of a tuple:

# SQL being all formal: My dear, please use full sentences 🎩 cursor.execute("SELECT * FROM my_table WHERE id = %s", (some_id,))

Or for libraries like sqlite3 with a question mark obsession:

# SQL being all mysterious: Who's that PokΓ©mon? πŸ•΅οΈβ€β™€οΈ cursor.execute("SELECT * FROM my_table WHERE id = ?", (some_id,))

Proper access pattern

When mingling with a Django model:

# The good way to ask for an ID: Could I have your name, please?🎟️ instance_id = MyModel.objects.all()[0].id

Avoid an integer's personal space:

# When you try to tickle an integer: Hey, that tickles! βœ‹ instance_id = MyModel.objects.all()[0].id[0] # Will induce a TypeError

String interpolation - The can of worms

Beware of encounters where string interpolation turns into a TypeError generator:

# That awkward moment when integer indexing ruins date night 😬 query = f"SELECT * FROM my_table WHERE id = {some_id[0]}" # Not if some_id is an int

Let the honourable library perform this interpolation through parameter substitution as shown above.

Building blocks of SQL query safety

Given the SQL Python dance floor's complexity, here are the non-negotiable rules to avoid such TypeError and other sneaky pitfalls.

Master Python iteration rituals

Stick to Python's iteration rule book to skirt around TypeErrors with non-iterable types.

Parsing interpolation formatters

The holy trinity of str.format, f-strings, or % formatters is the open sesame to TypeError-free queries.

cursor.execute() method, the saviour

Welfare check on cursor.execute()! Ensure it's treated well following your Python DB-API's guidance.

Unmasking the common culprits

Let's hunt down usual scenarios that sneak in a TypeError when dealing with integers and arm ourselves with resolutions.

Handling tuples like a pro

# Tuple having a 'me time', and we try to play third wheel πŸ‘¨β€πŸ‘¦β€πŸ‘¦ single_value = (42,) wrong_way = single_value[0][0] # Raises TypeError right_way = single_value[0] # Here's to respecting personal space

Unpacking like unpacking never done before

Unpack and unleash those query results when you're expecting but one value:

# Fetching a lone wolf age, = cursor.fetchone()

SQL query results and you

When a single value is all you expect from the query and fetchone() is your ally, keep your eyes peeled for a tuple:

rows = cursor.execute("SELECT MAX(age) FROM people").fetchone() # Age truly is just a number...until it's not πŸ€·β€β™€οΈ max_age = rows[0] if rows else None