Ask Your Question
0

How come abs(x) works?

asked 12 years ago

Eviatar Bach gravatar image

updated 12 years ago

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.

Preview: (hide)

1 Answer

Sort by » oldest newest most voted
3

answered 12 years ago

DSM gravatar image

updated 12 years ago

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. :-)

Preview: (hide)
link

Comments

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

kcrisman gravatar imagekcrisman ( 12 years ago )

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

kcrisman gravatar imagekcrisman ( 12 years ago )

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

Eviatar Bach gravatar imageEviatar Bach ( 12 years ago )

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: 12 years ago

Seen: 680 times

Last updated: Jun 12 '12