Code Snippets

Steve D'Aprano steve+python at pearwood.info
Wed Nov 1 20:24:59 EDT 2017


On Thu, 2 Nov 2017 04:25 am, Stefan Ram wrote:

>   I started to collect some code snippets:
[...]

> __import__( "random" ).random()
>
>   And so on. You get the idea.
>
>   However, reportedly, all those snippets are anti-patterns
>   because they use »__import__«.

Correct. Nearly all dunder functions and methods are reserved for use by the
interpreter.

It isn't an outright error to call __import__ directly, but you should avoid
it unless absolutely necessary.


[...]
>   What I'm supposed to do instead, I guess, is:
[...]

> import random
> ...
> random.random()
> 
>   Now, the user has to cut the import, paste it to the top
>   of his code, then go back to the list of snippets, find
>   the same snippet again, copy the expression, go to his code,
>   then find the point where he wanted to insert the snippet again,
>   and finally insert the snippet.

The ellipsis do nothing, why are they there? And surely you are capable of
copying two lines at a time.


import random
random.random()


requires only one copy operation.

There is no outright requirement to collect all the imports at the top of your
module. That's merely a very good convention to follow. If you don't mind
breaking the convention, you can simply paste the result where you want the
random number:

# code here
# more code
# paste here >>
import random
random.random()  # and edit as needed


This has saved you ten seconds of editing time while writing the code. It will
probably cost you ten minutes, when you come back to maintain the program in
six months and the imports are scattered all through the module, inside
functions and classes, but that's your decision to make.


>   And still there now is a 
>   risk of name collisions. So, it seems to me that __import__
>   is just so much better!

Only if you wish to write ugly, inefficient code.

The idea of code snippets is that they are intended as *templates*, not that
you repeat them over and over again. That would be the worst sort of copy and
paste programming, an anti-pattern.

If you need four random numbers, would you write this?


a = __import__( "random" ).random()
b = __import__( "random" ).random()
c = __import__( "random" ).random()
d = __import__( "random" ).random()


Or a list of them?


numbers = [__import__( "random" ).random() for i in range(1000)]


Do I need to explain how terrible that code is?

Code snippets are not an alternative to actually thinking about your code and
writing the best code you can.


-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list