this post was submitted on 12 Oct 2023
7 points (100.0% liked)

Python

6400 readers
24 users here now

Welcome to the Python community on the programming.dev Lemmy instance!

πŸ“… Events

PastNovember 2023

October 2023

July 2023

August 2023

September 2023

🐍 Python project:
πŸ’“ Python Community:
✨ Python Ecosystem:
🌌 Fediverse
Communities
Projects
Feeds

founded 1 year ago
MODERATORS
 

I'm talking about stuff like this: [file.unlink() for file in files] instead of the more verbose but maybe easier to grasp for python noobs:

for file in files:
    file.unlink()

Maybe with a bit more context:

def _cleanup(self) -> None:                                                                                                                                                                                                             
    dirs, files = partition(lambda f: f.is_file(), self._tmp_dir.rglob("*"))                                                                                                                                                            
    [file.unlink() for file in files]                                                                                                                                                                                                   
    [dir.rmdir() for dir in dirs]                                                                                                                                                                                                       
    self._tmp_dir.rmdir()
top 4 comments
sorted by: hot top controversial new old
[–] [email protected] 11 points 1 year ago

Typically I would expect for list comprehension to be used for data generation or filtering, so something like this definitely strikes odd when reading code and would just ask to unpack into classic loop

[–] nieceandtows 3 points 1 year ago

I don't think this is a good place to use list comprehension. Yes the code is smaller, but it is very hacky. It's like those flight booking hacks where you book for a different destination with your actual destination as a transit location. Yes it's cheaper, but that's not an elegant solution.

[–] slurp 1 points 1 year ago* (last edited 1 year ago) (1 children)

For me, the only reason I wouldn't do this is to include debug level logging of which files are being removed.

That said, how about using tempfile's TemporaryDirectory to handle the clearing up of the temporary directory?

[–] slurp 1 points 1 year ago

Though you might want to consider whether you want it to remove as much as possible in the case of permissions errors, in which case you might want exception handling around each unlink call, with it raising an exception after it's tried clearing everything if anything went wrong.