Ask Your Question
0

How come abs(x) works?

asked 2012-06-12 21:36:56 +0200

Eviatar Bach gravatar image

updated 2012-06-12 21:37:21 +0200

Hello,

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

sage: abs(x)
abs(x)
sage: bool(abs(x) == abs_symbolic(x))
True
sage: preparse('abs(x)')
'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
3

answered 2012-06-12 23:23:50 +0200

DSM gravatar image

updated 2012-06-12 23:23:59 +0200

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)
'fred'

The wonders of duck typing. :-)

edit flag offensive delete link more

Comments

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

kcrisman gravatar imagekcrisman ( 2012-06-13 00:00:52 +0200 )edit

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

kcrisman gravatar imagekcrisman ( 2012-06-13 00:01:24 +0200 )edit

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

Eviatar Bach gravatar imageEviatar Bach ( 2012-06-13 00:20:47 +0200 )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

Stats

Asked: 2012-06-12 21:36:56 +0200

Seen: 592 times

Last updated: Jun 12 '12