Ask Your Question

How come abs(x) works?

asked 2012-06-12 14:36:56 -0500

Eviatar Bach gravatar image

updated 2012-06-12 14:37:21 -0500


I notice that abs is a Python built-in function, but it also works symbolically:

sage: abs(x)
sage: bool(abs(x) == abs_symbolic(x))
sage: preparse('abs(x)')

What's going on here? Obviously the Python function should not accept a Sage type.

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted

answered 2012-06-12 16:23:50 -0500

DSM gravatar image

updated 2012-06-12 16:23:59 -0500

Obviously the Python function should not accept a Sage type.

Why not? Python's abs calls __abs__, if it exists:

>>> class NotABuiltinClass(object):
...     def __abs__(self):
...         return 'fred'
>>> a = NotABuiltinClass()
>>> abs(a)

The wonders of duck typing. :-)

edit flag offensive delete link more


You're like a Python tutorial waiting to happen, @DSM!

kcrisman gravatar imagekcrisman ( 2012-06-12 17:00:52 -0500 )edit

You forgot to include a doctest in your code here, very careless...

kcrisman gravatar imagekcrisman ( 2012-06-12 17:01:24 -0500 )edit

Ah, I see. I forgot about the existence of `__abs__`.

Eviatar Bach gravatar imageEviatar Bach ( 2012-06-12 17:20:47 -0500 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools


Asked: 2012-06-12 14:36:56 -0500

Seen: 354 times

Last updated: Jun 12 '12