Update of /cvsroot/py-howto/pyhowto
In directory usw-pr-cvs1:/tmp/cvs-serv16918
Modified Files:
doanddont.tex
Log Message:
Adding section about backslashes
Index: doanddont.tex
===================================================================
RCS file: /cvsroot/py-howto/pyhowto/doanddont.tex,v
retrieving revision 1.3
retrieving revision 1.4
diff -C2 -r1.3 -r1.4
*** doanddont.tex 2001/03/23 18:25:21 1.3
--- doanddont.tex 2001/03/25 20:05:22 1.4
***************
*** 90,93 ****
--- 90,120 ----
the rest of your code. Simply do not do that.
+ Bad examples:
+
+ \begin{verbatim}
+ >>> for name in sys.argv[1:]:
+ >>> exec "%s=1" % name
+ >>> def func(s, **kw):
+ >>> for var, val in kw.items():
+ >>> exec "s.%s=val" % var # invalid!
+ >>> execfile("handler.py")
+ >>> handle()
+ \end{verbatim}
+
+ Good examples:
+
+ \begin{verbatim}
+ >>> d = {}
+ >>> for name in sys.argv[1:]:
+ >>> d[name] = 1
+ >>> def func(s, **kw):
+ >>> for var, val in kw.items():
+ >>> setattr(s, var, val)
+ >>> d={}
+ >>> execfile("handle.py", d, d)
+ >>> handle = d['handle']
+ >>> handle()
+ \end{verbatim}
+
\subsection{from module import name1, name2}
***************
*** 100,103 ****
--- 127,154 ----
one module is reloaded, or changes the definition of a function at runtime.
+ Bad example:
+
+ \begin{verbatim}
+ # foo.py
+ a = 1
+
+ # bar.py
+ from foo import a
+ if something():
+ a = 2 # danger: foo.a != a
+ \end{verbatim}
+
+ Good example:
+
+ \begin{verbatim}
+ # foo.py
+ a = 1
+
+ # bar.py
+ import foo
+ if something():
+ foo.a = 2
+ \end{verbatim}
+
\subsection{except:}
***************
*** 256,259 ****
--- 307,343 ----
suited to parsing --- assuming you are ready to deal with the
\exception{ValueError} they raise.
+
+ \section{Using Backslash to Continue Statements}
+
+ Since Python treats a newline as a statement terminator,
+ and since statements are often more then is comfortable to put
+ in one line, many people do:
+
+ \begin{verbatim}
+ if foo.bar()['first'][0] == baz.quux(1, 2)[5:9] and \
+ calculate_number(10, 20) != forbulate(500, 360):
+ pass
+ \end{verbatim}
+
+ You should realize that this is dangerous: a stray space after the
+ \code{\\} would make this line wrong, and stray spaces are notoriously
+ hard to see in editors. In this case, at least it would be a syntax
+ error, but if the code was:
+
+ \begin{verbatim}
+ value = foo.bar()['first'][0]*baz.quux(1, 2)[5:9] \
+ + calculate_number(10, 20)*forbulate(500, 360)
+ \end{verbatim}
+
+ then it would just be subtly wrong.
+
+ It is usually much better to use the implicit continuation inside parenthesis:
+
+ This version is bulletproof:
+
+ \begin{verbatim}
+ value = (foo.bar()['first'][0]*baz.quux(1, 2)[5:9]
+ + calculate_number(10, 20)*forbulate(500, 360))
+ \end{verbatim}
\end{document}
|