Dynamically constructing a Boolean expression

I am writing code that increments the number at the end of a file name until it no longer overwrites the existing file. I create several files, all with the same base file name, but with different extensions, none of which I want to overwrite.

Naive version:

prefix = 'hello0' while os.path.exists(prefix + '.abc') or os.path.exists(prefix + '.def') or os.path.exists(prefix + '.ghi'): n = int(prefix[-1]) prefix = prefix[:-1] + str(n + 1) # I know this doesn't work when n reaches two digits; my full code involves a regular expression 

The condition can obviously be very long and ugly if there are several extensions. I rendered this in a for loop.

My version:

 prefix = 'hello0' extensions = ('.abc', '.def', '.ghi') # there could be even more than this condition = True while condition: condition = False # if any of the paths still exist, set the condition back to True for extension in extensions: if os.path.exists(prefix + extension): condition = True n = int(prefix[-1]) prefix = prefix[:-1] + str(n + 1) 

I still feel this is a bit awkward: it's not entirely clear what the while is actually testing. Is it possible to build a boolean expression dynamically and not set a boolean?

I think the following may work (I have not tested it, I only thought about it when writing this!), But I don’t think I need to resort to eval :

 prefix = 'hello0' extensions = ('.abc', '.def', '.ghi') test = 'False' for extension in extensions: test += " or os.path.exists(prefix + '" + extension + "')" while eval(test): n = int(prefix[-1]) prefix = prefix[:-1] + str(n + 1) 
+6
source share
1 answer

You might want to use the built-in any() with the generator:

 while any(os.path.exists(prefix + extension) for extension in extensions): # then increment prefix and try again, as in your example code 

This computes True or False , which you need with a simpler syntax.

In general, if I am ever tempted to use eval() in a dynamic language such as Python, then this means that there is an important language function that I need to learn about. Dynamic languages ​​should make the code beautiful without disaster, trying to write and save code-write-more-code, so you did exactly what here, asking about your approach.

+9
source

Source: https://habr.com/ru/post/925776/


All Articles