Xar
Xar

Reputation: 7910

Python: An integer is required. Where? Why?

I am having trouble with this brief code snippet:

for i, row in enumerate(rows):
    row["last_check"] = last_check_ts
    row_filtered = {
        k: v.replace('\r', '') for k, v in row.iteritems() if v is not None
    }

It gives me the following error:

k: v.replace('\r', '') for k, v in row.iteritems() if v is not None
TypeError: an integer is required

What am I doing wrong? Exactly what is supposed to be an integer?

Edit:

This is what rows looks like printed on console:

[{'COD_PER_FISICA': None, 'INCLUIDO_POR': 'FU', 'MODIFICADO_POR': None, 'ES_FISICA': 'N', 'COD_PERSONA': '37470', 'NOMBRE': 'BLABLA', 'COD_PER_JURIDICA': '37470', 'FECHA_MODIFICACION': None, 'FECHA_INCLUSION': datetime.datetime(2003, 6, 7, 18, 22, 13)},
{'COD_PER_FISICA': None, 'INCLUIDO_POR': 'FU', 'MODIFICADO_POR': 'FOO', 'ES_FISICA': 'N', 'COD_PERSONA': '37471', 'NOMBRE': 'blablabla', 'COD_PER_JURIDICA': '37471', 'FECHA_MODIFICACION': datetime.datetime(2003, 9, 2, 12, 14, 35), 'FECHA_INCLUSION': datetime.datetime(2003, 6, 7, 18, 22, 13)},
{'COD_PER_FISICA': None, 'INCLUIDO_POR': 'FU', 'MODIFICADO_POR': None, 'ES_FISICA': 'N', 'COD_PERSONA': '37472', 'NOMBRE': 'blablabala', 'COD_PER_JURIDICA': '37472', 'FECHA_MODIFICACION': None, 'FECHA_INCLUSION': datetime.datetime(2003, 6, 7, 18, 22, 13)},
{'COD_PER_FISICA': None, 'INCLUIDO_POR': 'FU', 'MODIFICADO_POR': None, 'ES_FISICA': 'N', 'COD_PERSONA': '37473', 'NOMBRE': 'blablabla', 'COD_PER_JURIDICA': '37473', 'FECHA_MODIFICACION': None, 'FECHA_INCLUSION': datetime.datetime(2003, 6, 7, 18, 22, 13)},
{'COD_PER_FISICA': None, 'INCLUIDO_POR': 'FU', 'MODIFICADO_POR': 'blablablaA', 'ES_FISICA': 'N', 'COD_PERSONA': '37474', 'NOMBRE': 'blablabla', 'COD_PER_JURIDICA': '37474', 'FECHA_MODIFICACION': datetime.datetime(2003, 9, 2, 12, 14, 19), 'FECHA_INCLUSION': datetime.datetime(2003, 6, 7, 18, 22, 13)}]

Upvotes: 0

Views: 134

Answers (1)

Two-Bit Alchemist
Two-Bit Alchemist

Reputation: 18457

Move this line:

row["last_check"] = last_check_ts

Below your dict comprehension. You can reproduce this as follows:

from datetime import datetime
rows = {'a': None, 'b': 'some_str\r', 'c': datetime.utcnow()}
{k: v.replace('\r', '') for k, v in rows.items() if v is not None}

You're adding a timestamp to your dict before looping over it, so one of the times you're calling v.replace('\r', '') the v object is actually a datetime. datetime objects do indeed have a replace method, but you're treating it like a string and therefore calling it with the wrong signature.

Upvotes: 6

Related Questions