on the popularity of loops while and for

Stestagg stestagg at gmail.com
Sat Aug 28 19:09:45 EDT 2021


On Sun, 29 Aug 2021 at 00:04, Stefan Ram <ram at zedat.fu-berlin.de> wrote:

> Stestagg <stestagg at gmail.com> writes:
> >If you're doing this analysis, I'd be pretty interested in how many of
> >those while loops where 'while True:'
>
>   Here, about 40 %.



Thanks!  That's an interesting stat.  I might have to look more into how
while loops are actually used in other people's code.


>
>   Below is a new version that is supposed to also count "if True:"
>   and "if 1:" and also removes a bug with the exception handling
>   (missing "import sys" and missing "UnicodeDecodeError"). I'm not
>   experienced in using the AST module, so there might still be bugs
>   in the program!
>
> import ast
> import pathlib
> import sys
> rootname=r'''PATH TO SOURCE DIR (WITHOUT A BACKQUOTE AT THE END)'''
> rootpath=pathlib.Path(rootname)
> rootiterable=rootpath.glob('**/*.py')
> WhileCount = 0
> TrueCount = 0
> ForCount = 0
> for filepath in rootiterable:
>     try:
>         with filepath.open(encoding="utf-8") as file:
>             source=file.read()
>             parse=ast.parse(source, filename=str(file))
>             for entry in ast.walk(parse):
>                 if isinstance(entry, ast.While):
>                     WhileCount+=1
>                     if ( isinstance( entry.test, ast.Constant ) and
>                           hasattr( entry.test, "value") and
>                           ( isinstance( entry.test.value, bool )
>                             and entry.test.value == True or
>                             isinstance( entry.test.value, int )
>                             and entry.test.value != 0 )):
>                         TrueCount+=1
>                     print( f"{ForCount=}, {WhileCount=}, {TrueCount=}" )
>                 elif isinstance(entry, ast.For):
>                     ForCount+=1
>                     print( f"{ForCount=}, {WhileCount=}" )
>     except ( SyntaxError, UnicodeDecodeError )as inst:
>        print( f"skipping {filepath}." )
>        print( f"{sys.exc_info()[ 0 ] =}" )
>        print( f"{type( inst ) =}" )
>        print( f"{inst.args =}" )
>        print( f"{inst =}\n" )
> print( f"{ForCount=}, {WhileCount=}, {TrueCount=}" )
>
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>


More information about the Python-list mailing list