[Tutor] Order of unittests
Peter Otten
__peter__ at web.de
Sat Oct 16 10:50:43 EDT 2021
On 16/10/2021 10:43, Albert-Jan Roskam wrote:
> On 15 Oct 2021 14:53, Peter Otten <__peter__ at web.de> wrote:
> ===>> Hi Peter,
> Thank you! That looks quite compact, so I'll give that a try on Monday. I
> could even use a lambda for my_dir(). I thought dir() was (re)implemented
> by defining, or in this case injecting, a __dir__ special method?
I should have warned that my my_dir()
> # shadow the dir() built-in with an order-preserving analogue
> def my_dir(obj):
> return list(vars(obj))
is but a sketch that only works in the exact case you gave, i. e. it
will miss __dir__(), inherited attributes, and probably something I
can't think of at the moment.
A low-effort improvement that at least will not miss any names might be
to use the built-in dir() to find the names and vars() to partially
(un)sort them:
# untested
def my_dir(obj):
names = dir(obj)
lookup = {n: i for i, n in enumerate(vars(obj))}
return sorted(names, key=lambda name: lookup.get(name, -1))
I'm sure someone has produced a more thorough implementation -- you just
have to find it ;)
More information about the Tutor
mailing list