Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adds support for PEP 519 File Path protocol #252

Merged
merged 12 commits into from
Mar 22, 2018
Merged

Adds support for PEP 519 File Path protocol #252

merged 12 commits into from
Mar 22, 2018

Conversation

jaden-young
Copy link
Contributor

Allows AudioSegment.from_file() and AudioSegment.export() to accept PathLike objects that represent file system paths, in addition to strings.

Python 3.4 introduced pathlib to make handling filesystem paths easier. In Python 3.6, PEP 519 added support for a new protocol to many builtin methods, such as open, to allow objects to signal that they represent filesystem paths by returning a str or bytes from a __fspath()__ method.

>>> from pydub import AudioSegment
>>> from pathlib import Path
>>> music_folder = Path('music')
>>> song_path = music_folder / 'my_song.mp3'
>>> song_audio = AudioSegment.from_file(song_path)
>>> song_audio.export(music_folder / 'my_song_backup.mp3')

Explicit support for the protocol is necessary since the utility method _fd_or_path_or_tempfile is expected to return anything that isn't a string that represents a path unaltered, and thus explicitly checks for string.

Also changed to checking isinstance instad of trying and excepting. Although this is taking more of a LBYL than an EAFP approach, catching the TypeError was actually swallowing a potential bug. We caught TypeError before for when the obj was not a str, bytes, or os.PathLike, but this actually hid the case when the obj implemented a faulty __fspath__.

os.fsdecode(x) calls x.__fspath__() and expects that to return a str or bytes, which it then decodes into a str. A type error is raised here if that __fspath__() call returned a bad type. We actually want this to be raised, since that implies a serious error in that object's __fspath__ function.
This line should have been removed when switching from equals to tolerance, but was accidentally left in during the commit.
@jiaaro jiaaro merged commit bad9eb0 into jiaaro:master Mar 22, 2018
@jaden-young jaden-young mentioned this pull request Jun 17, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants