What is the Python equivalent of static variables inside a function?

前端 未结 26 2748
天命终不由人
天命终不由人 2020-11-22 00:45

What is the idiomatic Python equivalent of this C/C++ code?

void foo()
{
    static int counter = 0;
    counter++;
          


        
26条回答
  •  不思量自难忘°
    2020-11-22 01:22

    Sure this is an old question but I think I might provide some update.

    It seems that the performance argument is obsolete. The same test suite appears to give similar results for siInt_try and isInt_re2. Of course results vary, but this is one session on my computer with python 3.4.4 on kernel 4.3.01 with Xeon W3550. I have run it several times and the results seem to be similar. I moved the global regex into function static, but the performance difference is negligible.

    isInt_try: 0.3690
    isInt_str: 0.3981
    isInt_re: 0.5870
    isInt_re2: 0.3632
    

    With performance issue out of the way, it seems that try/catch would produce the most future- and cornercase- proof code so maybe just wrap it in function

提交回复
热议问题