plumdog / flask_table

Because writing HTML is fiddly and all of your tables are basically the same
http://flask-table.readthedocs.org/
BSD 3-Clause "New" or "Revised" License
210 stars 45 forks source link

fix getting an empty element of table from dict #114

Closed Senusoid closed 2 years ago

plumdog commented 5 years ago

Hi!

Can you give an example of a problem this change is intended to fix?

Senusoid commented 5 years ago

Hi!

Can you give an example of a problem this change is intended to fix?

Hi,

1) exact case: i have header day of month and every row it`s a dict and i do

header = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31']
row = {'2': '8,5', '4': '4', '13': '3'}
table = TableCls(row, border=1)
table.__html__()

line 18, in _single_get val = getattr(item, key) AttributeError: 'dict' object has no attribute '1'

2) in comments:

First, try to lookup the key as if the item were a dict.

why check this with try/except instead of more obvious and correct way with isinstance?

plumdog commented 5 years ago

For 1, do you have a standalone example that generates the error? I'm not sure what header does in the code you posted. If you can post a full example that errors that would be useful.

For 2, trying with try-except vs isinstance is nearly a stylistic thing, but I would argue Python definitely pushes you towards try-except to account for things that do let you foo[key] but are not instances of dict. Eg:

class NotADict(object):
    def __getitem__(self, key):
        return 'got {}'.format(key)

not_a_dict = NotADict()

print(not_a_dict['foo'])
print(not_a_dict[1])
print('isinstance of dict? {}'.format(isinstance(not_a_dict, dict)))

outputs:

got foo
got 1
isinstance of dict? False

That is, it is not a dict, but it behaves like a dict. This is an example of Python's "duck typing".