jeudi 28 février 2019

Python 3: check that command runs without exception in "if .. else" block without using "try .. except"

Is there any native language construction in Python 3 to check if some line of code can be run without exception without using "try .. except" block?

E. g.: I parse a list of files and need to select only those files that start with UNIX-date and "_" symbol to and pass them to another module. I don't need neither the result of conversion at the moment, nor the type of exception nor the text of exception, only the fact that this file suites the requirements:

FileList = ["1550889019_FileName1.tar", "New_document.doc", "1550000000_FileName2.7z", "Song.mp3"] 
ValidFiles = []
for FileName in FileList:
    # Cut everything after first '_' symbol, convert to integer and try to parse as a date
    if no_exception(datetime.date.fromtimestamp(int(re.sub(r'_.*$', '', FileName)))):
        ValidFiles.append(FileName)

DoSmth(ValidFiles)

P. S.: I know that I can declare "no_exception()" function, run the code inside a "try .. except" block there and return false on exception, but I search for native "more elegant" solution right now.

Aucun commentaire:

Enregistrer un commentaire