[Tutor] redefining builtin function

Patrick K. O'Brien pobrien@orbtech.com
Wed, 12 Sep 2001 14:59:37 -0500


You need to explicitly import __builtins__. It is imported by default in the
shell, which is why your code worked interactively. You need to add an
import statement somewhere, like this:

def round(x,n=0):
    import __builtins__  # Add this.
    if n%1==0:
    ...

---
Patrick K. O'Brien
Orbtech (http://www.orbtech.com)
"I am, therefore I think."

-----Original Message-----
From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of
Christopher Smith
Sent: Wednesday, September 12, 2001 2:47 PM
To: tutor@python.org
Subject: [Tutor] redefining builtin function

Hi list,

I am trying to redefine a built in function.  I can do the following in
the
interactive window but not in a script.  Can anyone help me with the
script?

>>> from math import floor, log10
>>> def round(x,n=0):
...  if n%1==0:
...   return __builtins__.round(x,n)
...  return __builtins__.round(x,int(10*n)-1-floor(log10(abs(x))))
...
>>> print round(1.234567,2)
1.23
>>> print round(1.234567,0.2)
1.2
>>>

When I do the same thing in a script I get an "attribute error" so
apparently I am
working with a different namespace.  Is there a way to make sure that I
can get
access to the global _builtins__.round no matter where round is defined?

/c


_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor