Le mercredi 15 février 2012 à 15:55 -0800, Kevin Hunter a écrit :
> Can you expand on why? To me the former reads better, and elides the
> need to specifically import the Relational class:
>
"There should be one-- and preferably only one --obvious way to do it."
.is_Relational is an ad-hoc reimplementation of isinstance(), with
plenty of gotchas:
>>> Relational.is_Relational
True
>>> Eq(x, y).is_Equality
True
>>> Ne(x, y).is_Unequality
Traceback (most recent call last):
File "<ipython-input-21-c44de31e37c4>", line 1, in <module>
Ne(x, y).is_Unequality
AttributeError: 'Unequality' object has no attribute 'is_Unequality'
OTOH, isinstance() does what it says and its meaning is clear to any
Python programmer - there is no need to know beforehand that in sympy
is_SomeClass means isinstance(..., SomeClass) nor that is_integer is
completely different from is_Integer.
> >>> x.is_Relational
> True
>
> vs
>
> >>> from sympy.core.relational import Relational
> >>> isinstance(x, Relational)' reads better to me than 'isinstance(x,
> Relational)
It's actually a good thing that isinstance() is a bit cumbersome to
write. No matter how you spell it, such code introduces a tight coupling
with the class tested (therefore an explicit import is better than an
implicit coupling), and is hard to extend or override. isinstance()
calls also have a tendency to cluster in long elif chains, which devolve
quickly into spaghetti code. See, for instance,
sympy.core.function.count_ops().
> Further, the former is faster:
>
>
> In [11]: %timeit a.is_Relational
> 10000000 loops, best of 3: 76.3 ns per loop
>
>
> In [12]: %timeit isinstance(a, Relational)
> 1000000 loops, best of 3: 289 ns per loop
That kind of difference is usually completely negligible compared to
algorithmic improvements.
One last thing: all the is_Foo attributes live in the same namespace, so
if you want to have 2 classes with the same name, you can't (BTW, the
same problem exists in printers and ask handlers, with worse
consequences).
"Namespaces are one honking great idea -- let's do more of those!"
--
You received this message because you are subscribed to the Google Groups
"sympy" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/sympy?hl=en.