why sqrt is not a built-in function?

Chris Angelico rosuav at gmail.com
Fri Jan 15 17:57:28 EST 2021


On Sat, Jan 16, 2021 at 9:47 AM Michael F. Stemper <mstemper at gmail.com> wrote:
>
> On 15/01/2021 16.01, Chris Angelico wrote:
> > On Sat, Jan 16, 2021 at 8:56 AM Michael F. Stemper <mstemper at gmail.com> wrote:
> >>
> >> On 15/01/2021 15.26, Stefan Ram wrote:
> >>> "Michael F. Stemper" <mstemper at gmail.com> writes:
> >>>> On 15/01/2021 14.01, Stefan Ram wrote:
>
> >>>>> __import__( "math" ).sqrt( 4 )
> >>>> I had no idea that syntax existed, and find it completely at odds
> >>>> with The Zen of Python. I'm torn between forgetting that I ever saw
> >>>> it and using it for some evilly-obfuscated code.
> >>>
> >>>     When one collects snippets of Python code that are intended
> >>>     to be inserted into programs, a snippet usually would have
> >>>     to consist of two parts: One part to be inserted at the top
> >>>     of the program, into the imports section, and then the actual
> >>>     snippet.
> >>>     "__import__" allows to write snippets that can be inserted
> >>>     as they are without the need to do insertions at two different
> >>>     places. (Possibly with a tool to later normalize the insertions
> >>>     to the usual style.)
> >
> > I'm not sure how that works. In Python, you can just put the imports
> > where you want them - why would the __import__ function be needed?
>
> I have no idea what PEP-8 has to say on the subject. However, my coding
> style *generally* puts all of the imports up front, right after the
> prologue (program description, revision history, uzw).

Sure, and that's how I'd normally code too. But if I give you a
snippet like this:

from collections import Counter
ltr_weights = ''.join(Counter(text) & Counter(string.ascii_letters)).elements())

then it's absolutely fine to keep the import next to the code. There's
no need to go to the hassle of splitting the snippet; if you want to,
you can, but the snippet is still a single thing.

The __import__ function doesn't add anything here.

ChrisA


More information about the Python-list mailing list