cldf / csvw

CSV on the web
Apache License 2.0
37 stars 6 forks source link

Consider adding _len_ method to `Table` #30

Closed SimonGreenhill closed 4 years ago

SimonGreenhill commented 4 years ago

It would be useful to have a __len__ method on Table instances so this works:

if len(cldf['LanguageTable']):
   print("we have languages!")

...but I guess this requires iterating over all rows to know, so it's expensive (unless you want to try load that from the metadata)

xrotwang commented 4 years ago
if next(cldf['LanguageTable']):
    ...

should be cheap.

SimonGreenhill commented 4 years ago

btw -- next(cldf['table']) raises TypeError: 'Table' object is not an iterator, there's no Table.__next__()

xrotwang commented 4 years ago

Ah, so we should add that!

xflr6 commented 4 years ago

I don't think we want to make the table an exhaustable iterator (it is already iterable, AFAICT).

@xrotwang : maybe you meant if next(iter(clds['LanguageTable'])): above?

xflr6 commented 4 years ago

For the use case at hand it might be enough to add .__bool__() so we can do if cldf['LanguageTable']

xrotwang commented 4 years ago

Ah, yes. That sounds better.

Sebastian Bank notifications@github.com schrieb am Fr., 31. Jan. 2020, 18:35:

For the use case at hand it might be enough to add bool so we can do if cldf['LanguageTable']

— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/cldf/csvw/issues/30?email_source=notifications&email_token=AAGUOKGIOSDQS3RGLZZIKN3RAROPDA5CNFSM4KNAXCE2YY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGOEKPMZVI#issuecomment-580832469, or unsubscribe https://github.com/notifications/unsubscribe-auth/AAGUOKGLUBAWHN6W3DHYQTLRAROPDANCNFSM4KNAXCEQ .

xrotwang commented 4 years ago

Doing a bit more thinking, I'm now inclined to not add any method at all. Adding __bool__ would break backwards compatibility (think of code like pycldf.Dataset.add_table) which returns a table but might also return None - and checking the result with if table. And the missing __len__ method can be correctly interpreted as "that's hard (or expensive) to know".

Please re-open, if you disagree.