Re: Is this PEP-able? fwhile

2013-06-26 Thread Jan Riechers

On 26.06.2013 16:28, William Ray Wing wrote:

On Jun 26, 2013, at 7:49 AM, Fábio Santos fabiosantos...@gmail.com
mailto:fabiosantos...@gmail.com wrote:


On 26 Jun 2013 11:45, jim...@aol.com mailto:jim...@aol.com wrote:

 On Tuesday, June 25, 2013 9:30:54 PM UTC+5:30, Ian wrote:
  In my experience the sorts of people who preach one exit point are
  also all about defining preconditions and postconditions and proving
  that the postconditions follow from the preconditions.  I think that
  the two are linked, because the one exit point rule makes those
  sorts of proofs simpler.

 Ah! utopia!

 For every one who knows about pre/post/invariant conditions, there
are 10 who follow goto-statement-is-harmful like a religious edict.



 I just checked and MISRA-C 2012 now allows gotos in specific,
limited circumstances.  I think it was the MISRA-C 1998 standard that
caused all this trouble.  So if MISRA now allows goto, why not
Python  :)


What is the matter? Just use the goto module...




Wondered when that would be mentioned.

Personally, I've never found that much use for GoTo, but as old timers
know, that same module adds the Come_From entry point, which is
priceless.  ;-)

Bill





Actually, jumping to any place a program (I know it from QBasic :) ) is 
some kind of voodoo.


At first it seems that any function calling itself or calling another 
function from another function solves the goto puzzle - called OO 
programming, objects in space and inheritance?


But at 2nd glimpse, jumping in any place of code (function) or routine, 
at a given place precisely - and to avoid any checks and unrelated code 
which might occur on a regular function call and without the need to 
provide additional arguments - that's kinda cool (if variables are in 
scope by the target statements :) )


That's somehow how I remember it.

But I guess if everything should run as in a factory, one entrance, one 
component, one result and independently from each other (isolated) and 
on many cores and such, a goto without argument passing or state 
variables might just end up in a big mess.


What do you think?



--
http://mail.python.org/mailman/listinfo/python-list


Re: A certainl part of an if() structure never gets executed.

2013-06-18 Thread Jan Riechers

On 13.06.2013 20:00, Νικόλαος Κούρας wrote:

 if '-' not in name + month + year:
 cur.execute( '''SELECT * FROM works WHERE clientsID =
(SELECT id FROM clients WHERE name = %s) and MONTH(lastvisit) = %s and
YEAR(lastvisit) = %s ORDER BY lastvisit ASC''', (name, month, year) )
 elif '-' not in name + year:
 cur.execute( '''SELECT * FROM works WHERE clientsID =
(SELECT id FROM clients WHERE name = %s) and YEAR(lastvisit) = %s ORDER
BY lastvisit ASC''', (name, year) )
 elif '-' not in month + year:
 cur.execute( '''SELECT * FROM works WHERE MONTH(lastvisit)
= %s and YEAR(lastvisit) = %s ORDER BY lastvisit ASC''', (month, year) )
 elif '-' not in year:
 cur.execute( '''SELECT * FROM works WHERE YEAR(lastvisit) =
%s ORDER BY lastvisit ASC''', year )


This finally worked!



I spared myself to read the whole thread cause its super long and I find 
it admirable that some people took time to troubleshoot the issue and 
(even) added optimizations of what can be done differently/better.. even 
so it seems there was only a wrong char used in the ifs?..


And as a short note - you should add code which handles the worst-case 
scenario (everthing fails, nothing valid, avoid into code which might 
require variables/data which is not present and so forth..)



But generally speaking:
As a best practice in any language not just Python.
If you have the option to print out evaluations and values, use it!


As rule of thumb for debugging code:
1. Print out what values you get in (from user, in(to) a function)
2a. Test statements and logic either by setting a print (in your case 
inside each if) with something like if1, if2, ... else fired or 
what you prefer OR do a direct comparison if the evaluation statements 
are not super long (someone mentioned that..)
2b. In case of longer statements/calculations, break them into chunks, 
simplify the problem to smaller ones and try to verify the results as 
possible (being far apart and getting closer after each time is 
already a good hint in calculations..)
3. If you catch data from a database and you see now results - print 
out if your search/query even can return anything at all or if your 
query itself has a flaw or similar.


Optional but also useful:
4. On the end of a function, print if the output of the function is as 
expected


This small technique costs minimal time, but brings a brilliant ability:
1. Understand the code flow
2. Understand mistakes
3. Save yourself a big time by searching targeted for code parts which 
are executed..


..and ignore not directly connected code - for example when looking at 
other peoples code without documentation, comments or introduction.

This can spare loads of headaches.

And all this can be done in a couple of minutes..

Jan

--
http://mail.python.org/mailman/listinfo/python-list


Re: Python Game Development?

2013-06-08 Thread Jan Riechers

On 07.06.2013 18:53, letsplaysf...@gmail.com wrote:

I was planning on making a small 2D game in Python. Are there any libraries for 
this? I know of:

• Pygame - As far as I know it's dead and has been for almost a year
• PyOgre - Linux and Windows only(I do have those, but I want multi-platform)
• Cocos2D - Won't install and cant find any support
• PyCap - Can't find any documentation
• Panda3D - Dead since 2011 + overkill for what I need
• PyOpenGL - Overkill

Any help on what to do with this would be appreciated. I am making games mainly 
in Lua but I'd like to make one in Python for fun. I also understand that 
Python isn't exactly the *BEST* choice programming a game, but I have heard it 
is possible. Tell me if it's true. Thanks!



Hi,

I only have looked closer in pygame. But before asking for an general 
overview of possible gaming libraries, I would start to answer the 
question of what kind of game you want to make and what features do you 
really need.


For some space game for example it is most unlikely that you will face 
the requirement of having a bleeding edge physics engine. Especially if 
you make use of 2d objects versus 3d models of any type. I guess you can 
expand the latter to any extend here.


Also it is a common thing I might guess bravely, that the basics of game 
programming are done similar in all game engines.


- Setting up a game loop
- Calculation present and future ob objects
- Handling user input by using events
- Redraw the screen

And this is in pygame quite simply, but I also had trouble finding the 
right entrance to it, as you have to read a bit up on how components fit 
together in that library.


An example basic setup looks like (with classing), I remove my code and 
limited it to basic event/input handling and also the drawing of a 
screen object in which you can add images and stuff.


Sorry for the formatting, I copied from idle and formatted in my email 
client.


#

class gameApp:
def __init__(self):
pygame.init()
self.clock = pygame.time.Clock()

self.screen = pygame.display.set_mode( (640, 480), 
DOUBLEBUF|SRCALPHA )

self.run()


def run(self):
while not self.close_app:
self.clock.tick(60)

for event in pygame.event.get():
#print event

if event.type == KEYUP:
# Press tab for player info
if event.key == 9:
pass # Do something in tab key

elif event.type == MOUSEBUTTONDOWN:
if event.button == 1:
pass # Left click, mouse button is pressend

elif event.type == MOUSEMOTION:
mx = event.rel[0]
my = event.rel[1]
continue


elif event.type == QUIT:
self.close_app = True

self.screen.fill( (0,0,0) )
# Self interaction is a screen drawing object
self.screen.blit(self.interactions, (0,0), 
special_flags=BLEND_RGBA_ADD)


pygame.display.flip()



pygame.quit()


if __name__ == '__main__':
import pygame
from pygame.locals import *
gameApp()


#


Regards
Jan
--
http://mail.python.org/mailman/listinfo/python-list


Re: can anyone help me in developing a simple webpage in jinja2

2013-04-06 Thread Jan Riechers

On 06.04.2013 01:41, Satabdi Mukherjee wrote:

i am a rookie in python and i am trying to develop a simple webpage using 
jinja2.

can anyone please help me how to do that

i am trying in this way but showing invalid syntax error


[...]

 ul id=navigation
 {% for item in navigation %}
 lia href={{ item.href }}{{ item.caption }}/a/li
 {% endfor %}
 /ul

 h1My Webpage/h1
 {{ a_variable }}

[...]




Hello,

the jinja2 syntax is correct that way, see also this for reference for 
variable naming:

http://jinja.pocoo.org/docs/templates/index.html#variables

The invalid syntax is raised when? Can you post the error a bit more 
detailed, this will help giving you any advice.


If you know the code part raising the error and you post it, this will 
also help.


Jan
--
http://mail.python.org/mailman/listinfo/python-list


Re: Decorating functions without losing their signatures

2013-04-02 Thread Jan Riechers

On 03.04.2013 04:05, Rotwang wrote:

Hi all,

Here's a Python problem I've come up against and my crappy solution.
Hopefully someone here can suggest something better. I want to decorate
a bunch of functions with different signatures; for example, I might
want to add some keyword-only arguments to all functions that return
instances of a particular class so that the caller can create instances
with additional attributes. So I do something like this:

[...]

It seems to work, but I don't like it. Does anyone know of a better way
of doing the same thing?


Hi,

I think you might want to check out that Pycon2013 Video about Metaclass 
Prgoramming of David Beazley:

http://www.pyvideo.org/video/1716/python-3-metaprogramming

He explains how to passing attributes, such creating custom classes on 
demand and returning there signatures even when wrapped.


I think that was what you wanted to archive?

Regards
Jan
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python GUI questions

2013-03-31 Thread Jan Riechers

On 19.03.2013 21:01, maiden129 wrote:

Hello,

I'm using python 3.2.3 and I'm making a program that show the of occurrences of 
the character in the string in Tkinter.

My questions are:

How can I make an empty Entry object that will hold a word that a user will 
enter?

How to make an empty Entry object that will hold a single character that the 
user will enter?

 [..]



Hello,

here is a very good documentation about Tkinter and its most likely that 
the same principals of coding apply to Python 3.x when it comes down to 
the Tkinter part:

http://www.pythonware.com/library/tkinter/introduction/index.htm

Also as an tip, you can make use of a StringVar object for example - 
those are (if Im not completely wrong) meant to hold values which you 
can then access from the interface. Alike a binding to any element 
holding text. Which should take care of the updating part if you call a 
proper StringVar/yourVariableName.set method of that particular class.


As for the UI creation, have a look at that documentation, its very easy 
to navigate inside if you know what you are looking for.


Regards
Jan


--
http://mail.python.org/mailman/listinfo/python-list


Re: pylint, was Re: pygame - importing GL - very bad...

2013-01-05 Thread Jan Riechers

On 05.01.2013 03:11, someone wrote:

On 01/03/2013 12:27 PM, Chris Angelico wrote:

On Thu, Jan 3, 2013 at 10:19 PM, someone newsbo...@gmail.com wrote:

Doesn't this [ ... ] mean something optional?

What does {2,30}$ mean?

I think $ means that the {2,30} is something in the end of the
sentence...


You can find regular expression primers all over the internet, but to
answer these specific questions: [...] means any of the characters in
the range; the $ means end of string; and {2,30} means at least two,
and at most thirty, of the preceding character. So you have to have
one from the first group, then 2-30 from the second, for a total of
3-31 characters in your names.


Got it, thanks!




Just following the discussion which is very interesting, even so when 
not working with OpenGL (which looks like a nightmare with that naming 
space) :)


But about the regular expressions (a bit deeper look into that):
Like said of Chris:

[a-z]
defines a catching group, in this case all ascii lowercase letters 
ranging from a to z. If noting else is provided, the rule matches 
one letter if there is no range defined by something like:

{} - Target a range of a match/hit

There are also a
? - Lazy match
* - Gready match

[A-Z][0-9]{1,3} means translated:
Look for any uppercase letter in ascii(!) (not öäü or similiar) 
ranging from A to Z.


Now look for any digit (2nd catching group) with the addition to satisfy 
the rule ONLY if there are at least 1 to 3 digits found.
Note: If there are 4 or more digits - the catching rule is still 
satisfied and will provide a match/hit.


If there is a follow up group, the next evaluation is gone through if 
present and so forth. If the expression is satisfied, the match is returned.


The lazy ? and greedy * matches try to satisfy, as the naming 
implies, to match as less or as much of what you have asked for.


For example the regular expression is valid:
0* - Look for a zero, and be greedy as of how many zeros you want match 
which might follow.


Regular expressions don't have to include catching groups in order to work.

But when you use them yourself somehow, its quite simple I think.
I guess you are anyhow busy mangling with pyLint, PEP-Standards and 
pyOpenGL - so good luck with that :)


Jan Riechers

--
http://mail.python.org/mailman/listinfo/python-list


Re: New image and color management library for Python 2+3

2012-08-23 Thread Jan Riechers


On 20.08.2012 20:34, Christian Heimes wrote:
 Am 19.08.2012 19:35, schrieb Jan Riechers:

 Hello Jan,

 we decided against ImageMagick and pgmagick for several reasons. For one
 we were already using FreeImage in other projects (Delphi projects and
 through ctypes binding with FreeImagePy).

[SNIP]

 The Python bindings for ImageMagick weren't that good and today they are
 still buggy. For example I'm not able to set the resize filter to a high
 quality setting like Catmull-Rom-Spline with the most recent version of
 pgmagick. filterType() doesn't do anything. The output image still has
 the same MD5 hash.

 ImageMagick and PIL were missing important features, too. For example
 both libraries don't support color management with lcms2 nor cached
 color transformations nor introspection of ICC profiles. They use lcms1.


The color profiles explains - perhaps it would be interesting still to 
test out your library with regular images (without color profiles) 
against ImageMagick, just to compare the raw speed of both solutions. In 
my case I really would love to see if there is a even higher performance 
solution available as I plan to serve a lot of users a time and 
especially keeping the Input/Output during file writing low would be 
very helpful.




 Can you perhaps test your solution with ImageMagick (as it is used
 widely) it would be interesting so.

 I've added some more benchmark results to the README.txt (PIL with
 non-standard libjpeg-turbo and pgmagick). The results are available at
 https://bitbucket.org/tiran/smc.freeimage

 Spoiler: pgmagick isn't faster and its resize filter settings don't work.

Thank you for the additional benchmarks, nice to read!

I will try your library out to see how it compares to old-pendant 
ImageMagick with Pypy 1.9 | Wand / Pillow (Pil fork for pypy) and Python 
2.7.3 PIL / ImageMagick - perhaps I can deliver you those numbers too - 
for those folks not completely in need of a color profile aware version 
but to compare raw numbers


Perhaps it would also be nice to see if and how it works with Pypy too

Jan
--
http://mail.python.org/mailman/listinfo/python-list


Re: New image and color management library for Python 2+3

2012-08-19 Thread Jan Riechers

On 14.08.2012 21:22, Christian Heimes wrote:

Hello fellow Pythonistas,


Performance
===

smc.freeimage with libjpeg-turbo read JPEGs about three to six times
faster than PIL and writes JPEGs more than five times faster.


[]


Python 2.7.3
read / write cycles: 300
test image: 1210x1778 24bpp JPEG (pon.jpg)
platform: Ubuntu 12.04 X86_64
hardware: Intel Xeon hexacore W3680@3.33GHz with 24 GB RAM

smc.freeimage, FreeImage 3.15.3 standard
  - read JPEG 12.857 sec
  - read JPEG 6.629 sec (resaved)
  - write JPEG 21.817 sec
smc.freeimage, FreeImage 3.15.3 with jpeg turbo
  - read JPEG 9.297 sec
  - read JPEG 3.909 sec (resaved)
  - write JPEG 5.857 sec
  - read LZW TIFF 17.947 sec
  - read biton G4 TIFF 2.068 sec
  - resize 3.850 sec (box)
  - resize 5.022 sec (bilinear)
  - resize 7.942 sec (bspline)
  - resize 7.222 sec (bicubic)
  - resize 7.941 sec (catmull rom spline)
  - resize 10.232 sec (lanczos3)
  - tiff numpy.asarray() with bytescale() 0.006 sec
  - tiff load + numpy.asarray() with bytescale() 18.043 sec
PIL 1.1.7
  - read JPEG 30.389 sec
  - read JPEG 23.118 sec (resaved)
  - write JPEG 34.405 sec
  - read LZW TIFF 21.596 sec
  - read biton G4 TIFF: decoder group4 not available
  - resize 0.032 sec (nearest)
  - resize 1.074 sec (bilinear)
  - resize 2.924 sec (bicubic)
  - resize 8.056 sec (antialias)
  - tiff scipy fromimage() with bytescale() 1.165 sec
  - tiff scipy imread() with bytescale() 22.939 sec



Christian



Hello Christian,

I'm sorry for getting out of your initial question/request, but did you 
try out ImageMagick before making use of FreeImage - do you even perhaps 
can deliver a comparison between your project and ImageMagick (if 
regular Python is used)?


I ask cause:
Im in the process of creating a web-app which also requires image 
processing and just switching from PIL (because it is unfortunately not 
that quick as it should be) to ImageMagick and the speeds are much 
better compared to it, but I didn't take measurements of that.


Can you perhaps test your solution with ImageMagick (as it is used 
widely) it would be interesting so. :)


But no offence by that and respect for you work so!

Jan
--
http://mail.python.org/mailman/listinfo/python-list


Re: the meaning of rユ.......ï¾

2012-07-23 Thread Jan Riechers

On 23.07.2012 16:55, Henrik Faber wrote:

On 23.07.2012 15:52, Henrik Faber wrote:


but I would hate for
Python to include them into identifiers. Then again, I'm pretty sure
this is not planned anytime soon.


Dear Lord.

Python 3.2 (r32:88445, Dec  8 2011, 15:26:58)
[GCC 4.5.2] on linux2
Type help, copyright, credits or license for more information.

fööbär = 3
fööbär

3

I didn't know this. How awful.

Regards,
Johannes



I can't understand at all why this (even as German) is supported.

Programs and developments, and in particular Python, should not only be 
accessible but also understandable by everyone - meaning that I don't 
exclude folks by starting to write my code in Esperanto letters.


Otherwise the next thing one might working on is a script normalizer 
which Engli-fies foreign variable names... similar to Py2to3.


Outside for display usage it has a right place to make usage of Unicode, 
like for French with all the accents Danish, Swedish and other 
languages, but some old-standards should stay in place, meaning to use 
English, so it stays accessible and understandable.


Jan
--
http://mail.python.org/mailman/listinfo/python-list


Re: Converting a list of strings into a list of integers?

2012-07-22 Thread Jan Riechers

On 22.07.2012 18:39, Alister wrote:

On Sun, 22 Jul 2012 10:29:44 -0500, Tony the Tiger wrote:

I came up with the following:

# options.modus_list contains, e.g., [2,3,4]
#   (a string from the command line)
# MODUS_LIST contains, e.g., [2,4,8,16]
#   (i.e., a list of integers)

 if options.modus_list:
 intTmp = []
 modTmp = options.modus_list[1:-1]
 for itm in modTmp:
 intTmp.append(int(itm))
 MODUS_LIST = intTmp


TIA


  /Grrr


looks like a classic list comprehension to me and can be achieved in a
single line

MODUS_LIST=[int(x) for x in options.modus_list]





Hi,

I am not sure why everyone is using the for-iterator option over a 
map, but I would do it like that:


MODUS_LIST= map(int, options.modus_list)

map works on a list and does commandX (here int conversion, use 
str for string.. et cetera) on sequenceY, returning a sequence. More 
in the help file.


And if I'm not completely mistaken, it's also the quicker way to do 
performance wise. But I can't completely recall the exact reason.


Jan
--
http://mail.python.org/mailman/listinfo/python-list


Re: Converting a list of strings into a list of integers?

2012-07-22 Thread Jan Riechers

On 22.07.2012 20:03, David Robinow wrote:

On Sun, Jul 22, 2012 at 12:20 PM, Jan Riechers janpet...@freenet.de wrote:

On 22.07.2012 18:39, Alister wrote:

looks like a classic list comprehension to me and can be achieved in a
single line
MODUS_LIST=[int(x) for x in options.modus_list]

Hi,

I am not sure why everyone is using the for-iterator option over a map,
but I would do it like that:
MODUS_LIST= map(int, options.modus_list)

map works on a list and does commandX (here int conversion, use str
for string.. et cetera) on sequenceY, returning a sequence. More in the help
file.

And if I'm not completely mistaken, it's also the quicker way to do
performance wise. But I can't completely recall the exact reason.

  Because if you don't have a functional background 'map' is
unfamiliar. Although I've been aware of it for years I still can't
remember if it's map(int, list) or map(list,int) and although with a
small effort I could force it into my brain, I know that many of the
people reading my code are as ignorant as I am. The list comprehension
seems clearer to me.




Hello,

no offense by that, I just was wondering why everyone uses the list 
comprehension instead the built-in map in this case - I'm still using 
Python 2.7.3 so perhaps things might have changed a little. :)


So far
Jan
--
http://mail.python.org/mailman/listinfo/python-list


Re: Converting a list of strings into a list of integers?

2012-07-22 Thread Jan Riechers

On 22.07.2012 20:01, Steven D'Aprano wrote:
[SNIP]

map is faster than an ordinary for-loop if the function you are applying
is a builtin like int, str, etc. But if you have to write your own pure-
Python function, the overhead of calling a function negates the advantage
of map, which is no faster than a for-loop. For example:

results = map(int, sequence)  # calls builtin `int`

hoists the call to int into the fast C layer, instead of the slow Python
layer, and should be faster than

results = []
for x in sequence:
 results.append(int(x))

which runs at the speed of Python. But:

results = map(lambda x: x+1, sequence)  # calls pure Python function

if no faster than a for-loop:

results = []
for x in sequence:
 results.append(x+1)

Note: this has*nothing*  to do with the use of lambda. Writing the +1
function above using def instead of lambda would give the same results.

[SNAP]

Hi Steven,

besides that I testdrive Pypy (and still am impressed, other topic) - 
your answer was what I was picking for ;)


Especially this part of you:
 map is faster than an ordinary for-loop if the function you are applying
 is a builtin like int, str, etc. [underlaying c-layer] But if you 
have to write your own pure-

 Python function, the overhead of calling a function negates the advantage
 of map [...]

I did not know that the speed gain is up foremost present when using 
built-ins, but that's for sure something to keep in mind when writing code.


Thanks for your explanation, clarifies a lot!

Jan
--
http://mail.python.org/mailman/listinfo/python-list


Basic question about speed/coding style/memory

2012-07-21 Thread Jan Riechers

Hello Pythonlist,

I have one very basic question about speed,memory friendly coding, and 
coding style of the following easy if-statement in Python 2.7, but Im 
sure its also the same in Python 3.x


Block
#--
if statemente_true:
doSomething()
else:
doSomethingElseInstead()

#--

versus this block:
#--
if statement_true:
doSomething()
return

doSomethingElseInstead()

#--


I understand the first pattern that I tell the interpreter to do:
Check if the conditional is true, run doSomething() else go inside the 
else block and doSomethingElseInstead().


while the 2nd does only checks:
doSomething() if statement_true, if not, just go directly to 
doSomethingElseInstead()



Now, very briefly, what is the better way to proceed in terms of 
execution speed, readability, coding style?
Letting out the fact that, in order to prevent 
doSomethingElseInstead-Block to execute, a return has to provided.


Thank you for reading and hope someone brings light into that.

Your fellow python programmer
Jan
--
http://mail.python.org/mailman/listinfo/python-list


Re: Basic question about speed/coding style/memory

2012-07-21 Thread Jan Riechers

On 21.07.2012 11:02, Andrew Berg wrote:

On 7/21/2012 2:33 AM, Jan Riechers wrote:

Block
...
versus this block:
...
Now, very briefly, what is the better way to proceed in terms of
execution speed, readability, coding style?

Using if/else is the most readable in the general sense. Using return
(or break or continue as applicable) in this manner would indicate (at
least to me) that it's an exceptional or otherwise special case and that
the function can't do what it's supposed to. In that case, I would try
to catch an exception rather than use if/else whenever possible. I
highly doubt there is a significant performance difference between them.



Hello Andrew,

Your answer is right, in other circumstances I also would stick to 
try/except, break-statements in loops and so forth.

But the question was a bit more elementary.

Cause, as I understand the interpreter chooses either the else (1st 
block) or just proceeds with following code outside the if.


So if there is some overhead in some fashion in case we don't offer the 
else, assuming the interpreter has to exit the evaluation of the 
if-statement clause and return to a normal parsing code-state 
outside the if statement itself.


I hope this explanation makes more sense in what I want to ask ;)

Jan
--
http://mail.python.org/mailman/listinfo/python-list


Re: Basic question about speed/coding style/memory

2012-07-21 Thread Jan Riechers

On 21.07.2012 12:06, Steven D'Aprano wrote:


But in general, you're worrying too much about trivia. One way or the
other, any speed difference will be trivial. Write whatever style reads
and writes most naturally, and only worry about what's faster where it
actually counts.





Notice that I try to make each function do the same amount of work, so
that we're seeing only the difference between else vs no else.

Now let's test the speed difference with Python 2.7. Because this is
timing small code snippets, we should use the timeit module to time the
code:

from timeit import Timer
setup = from __main__ import with_else, without_else
t1 = Timer(for i in (0, 1): result = with_else(i), setup)
t2 = Timer(for i in (0, 1): result = without_else(i), setup)

Each snippet calls the function twice, once to take the if branch, then
to take the else branch.

Now we time how long it takes to run each code snippet 100 times. We
do that six times each, and print the best (lowest) speed:

py min(t1.repeat(repeat=6))
0.9761919975280762
py min(t2.repeat(repeat=6))
0.9494419097900391

So there is approximately 0.03 second difference per TWO MILLION
if...else blocks, or about 15 nanoseconds each. This is highly unlikely
to be the bottleneck in your code. Assuming the difference is real, and
not just measurement error, the difference is insignificant.

So, don't worry about which is faster. Write whichever is more natural,
easier to read and write.




Hello Steven,

very nice example and thank you very much for also for the Timeit test!
Actually it confirms my assumption in some way:

[SNIP myself]
So if there is some overhead in some fashion in case we don't offer the
else, assuming the interpreter has to exit the evaluation of the
if-statement clause and return to a normal parsing code-state
outside the if statement itself.
[SNAP]

Without having looked at Andrew's bytecode excecution hint, using the 
dis module, to see how the interpreter handles the task on lower level.


But fare enough for me :)

But I agree, the return in my example is misleading and it would be 
illegal outside of a function call. I just added it to make clear that 
the fellow code below the return should not be executed in comparison to 
the 2nd example.


Thank you very much
Jan
--
http://mail.python.org/mailman/listinfo/python-list