[Tutor] Python conundrum
Marc Tompkins
marc.tompkins at gmail.com
Thu Jul 7 19:15:37 CEST 2011
On Thu, Jul 7, 2011 at 7:30 AM, Noah Hall <enalicho at gmail.com> wrote:
> On Thu, Jul 7, 2011 at 3:17 PM, Lisi <lisi.reisz at gmail.com> wrote:
> > Hi! :-)
> >
> > >From the book I am working from:
> >
> > <quote> A shortcut is to do your import like this:
> > from ex25 import * </quote>
> >
> > Is this a new and wonderful meaning of the word "shortcut"?
>
I haven't read the book in question, so I don't know whether they cover this
in the next paragraph... but this is generally BAD PRACTICE. If the module
you're importing contains functions that have the same names as functions in
the standard library, or in another module that you're also importing, then
_the last thing you import prevails._ If that was really what you wanted,
well and good - but it's very, very easy to make mistakes this way, and
frustratingly hard to catch them.
To take an extreme example, imagine that you're importing a module called
"bogus", and that "bogus" contains a function called "int()" function which
actually returns a random number. (Why? 'Cause I'm making a point here,
that's why!) In this hypothetical example, if you import "bogus" in the
usual way -
> import bogus
> int("5")
> >> 5
> bogus.int("5")
> >> 97
>
you get what you'd expect. But if you use the nifty "shortcut" method
(SOOOO much easier!) you might get the following:
> import * from bogus
> int("5")
> >> 63
>
Huh?
>
And again, if that's what you want, more power to you. But I prefer to
overload methods explicitly so that I know what code will run when I call a
function.
To be clear: most modules don't randomly overload standard methods... much.
One common exception is str(); many classes offer custom str() methods, and
calling a custom method when you're expecting the standard one can waste
your whole day.
In the words of the great philosopher "import this" - "Namespaces are one
honking great idea -- let's do more of those!"
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110707/0fe76b0d/attachment.html>
More information about the Tutor
mailing list