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

replacing %s with f-string #1165

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ Add your changes below.
- Audiobook integration tests
- Edited docstrings for certain functions in client.py for functions that are no longer in use and have been replaced.
- `current_user_unfollow_playlist()` now supports playlist IDs, URLs, and URIs rather than previously where it only supported playlist IDs.
- replaced %s strings with f-strings

### Removed
- `mock` no longer listed as a test dependency. Only built-in `unittest.mock` is actually used.
Expand Down
9 changes: 3 additions & 6 deletions examples/artist_albums.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,7 @@ def get_args():
def get_artist(name):
results = sp.search(q='artist:' + name, type='artist')
items = results['artists']['items']
if len(items) > 0:
return items[0]
else:
return None
return items[0] if items else None


def show_artist_albums(artist):
Expand All @@ -38,7 +35,7 @@ def show_artist_albums(artist):
for album in albums:
name = album['name']
if name not in seen:
logger.info('ALBUM: %s', name)
logger.info(f'ALBUM: {name}')
seen.add(name)


Expand All @@ -48,7 +45,7 @@ def main():
if artist:
show_artist_albums(artist)
else:
logger.error("Can't find artist: %s", artist)
logger.error(f"Can't find artist: {artist}")


if __name__ == '__main__':
Expand Down
17 changes: 7 additions & 10 deletions examples/artist_discography.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,7 @@ def get_args():
def get_artist(name):
results = sp.search(q='artist:' + name, type='artist')
items = results['artists']['items']
if len(items) > 0:
return items[0]
else:
return None
return items[0] if items else None


def show_album_tracks(album):
Expand All @@ -34,7 +31,7 @@ def show_album_tracks(album):
results = sp.next(results)
tracks.extend(results['items'])
for i, track in enumerate(tracks):
logger.info('%s. %s', i + 1, track['name'])
logger.info(f"{i + 1}. {track['name']}")


def show_artist_albums(artist):
Expand All @@ -44,21 +41,21 @@ def show_artist_albums(artist):
while results['next']:
results = sp.next(results)
albums.extend(results['items'])
logger.info('Total albums: %s', len(albums))
logger.info(f'Total albums: {len(album)}')
unique = set() # skip duplicate albums
for album in albums:
name = album['name'].lower()
if name not in unique:
logger.info('ALBUM: %s', name)
logger.info(f"ALBUM: {name}")
unique.add(name)
show_album_tracks(album)


def show_artist(artist):
logger.info('====%s====', artist['name'])
logger.info('Popularity: %s', artist['popularity'])
logger.info(artist['name'].center(10, '='))
logger.info(f'Popularity: {artist['popularity']}')
if len(artist['genres']) > 0:
logger.info('Genres: %s', ','.join(artist['genres']))
logger.info(f"Genres: {','.join(artist['genres'])}")


def main():
Expand Down
8 changes: 2 additions & 6 deletions examples/artist_recommendations.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,17 +22,13 @@ def get_args():
def get_artist(name):
results = sp.search(q='artist:' + name, type='artist')
items = results['artists']['items']
if len(items) > 0:
return items[0]
else:
return None
return items[0] if items else None


def show_recommendations_for_artist(artist):
results = sp.recommendations(seed_artists=[artist['id']])
for track in results['tracks']:
logger.info('Recommendation: %s - %s', track['name'],
track['artists'][0]['name'])
logger.info(f"Recommendation: {track['name']} - {track['artists'][0]['name']}")


def main():
Expand Down
5 changes: 1 addition & 4 deletions examples/audio_analysis_for_track.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,7 @@
client_credentials_manager = SpotifyClientCredentials()
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)

if len(sys.argv) > 1:
tid = sys.argv[1]
else:
tid = 'spotify:track:4TTV7EcfroSLWzXRY6gLv6'
tid = sys.argv[1] if len(sys.argv) > 1 else 'spotify:track:4TTV7EcfroSLWzXRY6gLv6'
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I won't add these changes, it makes the code a bit harder to read, considering these are just examples.


start = time.time()
analysis = sp.audio_analysis(tid)
Expand Down
5 changes: 1 addition & 4 deletions examples/audio_features.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,7 @@
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
sp.trace = False

if len(sys.argv) > 1:
artist_name = ' '.join(sys.argv[1:])
else:
artist_name = 'weezer'
artist_name = ' '.join(sys.argv[1:]) if len(sys.argv) > 1 else 'weezer'

results = sp.search(q=artist_name, limit=50)
tids = []
Expand Down
11 changes: 2 additions & 9 deletions examples/follow_playlist.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,8 @@ def get_args():

def main():
args = get_args()

if args.playlist is None:
# Uses the Spotify Global Top 50 playlist
spotipy.Spotify(auth_manager=SpotifyOAuth()).current_user_follow_playlist(
'37i9dQZEVXbMDoHDwVN2tF')

else:
spotipy.Spotify(auth_manager=SpotifyOAuth()).current_user_follow_playlist(args.playlist)

playlist = args.playlist or '37i9dQZEVXbMDoHDwVN2tF' # default is Spotify Global Top 50 playlist
Copy link
Member

@dieser-niko dieser-niko Dec 3, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

actually needed to use a different playlist because Spotify blocks access to their own playlists now.

spotipy.Spotify(auth_manager=SpotifyOAuth()).current_user_follow_playlist(playlist)

if __name__ == '__main__':
main()
2 changes: 1 addition & 1 deletion examples/my_playlists.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,4 @@

results = sp.current_user_playlists(limit=50)
for i, item in enumerate(results['items']):
print("%d %s" % (i, item['name']))
print(f"{i}, {item['name']}")
3 changes: 1 addition & 2 deletions examples/show_my_saved_tracks.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,7 @@
def show_tracks(results):
for item in results['items']:
track = item['track']
print("%32.32s %s" % (track['artists'][0]['name'], track['name']))

print(f"{track['artists'][0]['name']:<32.32} {track['name']}")

sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope))

Expand Down
4 changes: 1 addition & 3 deletions examples/user_playlists_contents.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,7 @@
def show_tracks(results):
for i, item in enumerate(results['items']):
track = item['track']
print(
" %d %32.32s %s" %
(i, track['artists'][0]['name'], track['name']))
print(f"{i:2d} {track['artists'][0]['name']:<32.32} {track['name']}")


if __name__ == '__main__':
Expand Down
14 changes: 3 additions & 11 deletions examples/user_public_playlists.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,6 @@

while playlists:
for i, playlist in enumerate(playlists['items']):
print(
"%4d %s %s" %
(i +
1 +
playlists['offset'],
playlist['uri'],
playlist['name']))
if playlists['next']:
playlists = sp.next(playlists)
else:
playlists = None
print(f"{i + 1 + playlists['offset']:4d} {playlist['uri']} {playlist['name']}")

playlists = sp.next(playlists) if playlists['next'] else None
8 changes: 4 additions & 4 deletions spotipy/cache_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,9 +83,9 @@ def get_cached_token(self):

except OSError as error:
if error.errno == errno.ENOENT:
logger.debug("cache does not exist at: %s", self.cache_path)
logger.debug(f"cache does not exist at: {self.cache_path}")
else:
logger.warning("Couldn't read cache at: %s", self.cache_path)
logger.warning(f"Couldn't read cache at: {self.cache_path}")

return token_info

Expand All @@ -95,8 +95,7 @@ def save_token_to_cache(self, token_info):
f.write(json.dumps(token_info, cls=self.encoder_cls))
f.close()
except OSError:
logger.warning('Couldn\'t write token to cache at: %s',
self.cache_path)
logger.warning(f"Couldn\'t write token to cache at: {self.cache_path}")


class MemoryCacheHandler(CacheHandler):
Expand Down Expand Up @@ -214,6 +213,7 @@ def save_token_to_cache(self, token_info):
class MemcacheCacheHandler(CacheHandler):
"""A Cache handler that stores the token info in Memcache using the pymemcache client
"""

def __init__(self, memcache, key=None) -> None:
"""
Parameters:
Expand Down
12 changes: 6 additions & 6 deletions spotipy/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -263,8 +263,9 @@ def _internal_call(self, method, url, payload, params):
if self.language is not None:
headers["Accept-Language"] = self.language

logger.debug('Sending %s to %s with Params: %s Headers: %s and Body: %r ',
method, url, args.get("params"), headers, args.get('data'))
logger.debug(
f"Sending {method} to {url} with Params: {args.get('params')} \
Headers: {headers} and Body: {args.get('data')!r}")

try:
response = self._session.request(
Expand All @@ -290,9 +291,8 @@ def _internal_call(self, method, url, payload, params):
reason = None

logger.error(
'HTTP Error for %s to %s with Params: %s returned %s due to %s',
method, url, args.get("params"), response.status_code, msg
)
f'HTTP Error for {method} to {url} with Params: {args.get("params")} \
returned {response.status_code} due to {msg}')

raise SpotifyException(
response.status_code,
Expand All @@ -317,7 +317,7 @@ def _internal_call(self, method, url, payload, params):
except ValueError:
results = None

logger.debug('RESULTS: %s', results)
logger.debug(f'RESULTS: {results}')
return results

def _get(self, url, args=None, payload=None, **kwargs):
Expand Down
52 changes: 24 additions & 28 deletions spotipy/oauth2.py
Original file line number Diff line number Diff line change
Expand Up @@ -218,8 +218,8 @@ def _request_access_token(self):
)

logger.debug(
"sending POST request to %s with Headers: %s and Body: %r",
self.OAUTH_TOKEN_URL, headers, payload
f"Sending POST request to {self.OAUTH_TOKEN_URL} \
with Headers: {headers} and Body: {payload!r}"
)

try:
Expand Down Expand Up @@ -401,20 +401,18 @@ def _open_auth_url(self):
auth_url = self.get_authorize_url()
try:
webbrowser.open(auth_url)
logger.info("Opened %s in your browser", auth_url)
logger.info(f"Opened {auth_url} in your browser")
except webbrowser.Error:
logger.error("Please navigate here: %s", auth_url)
logger.error(f"Please navigate here: {auth_url}")

def _get_auth_response_interactive(self, open_browser=False):
if open_browser:
self._open_auth_url()
prompt = "Enter the URL you were redirected to: "
else:
url = self.get_authorize_url()
prompt = (
"Go to the following URL: {}\n"
"Enter the URL you were redirected to: ".format(url)
)
prompt = (f"Go to the following URL: {url}\nEnter the URL you were redirected to: ")

response = self._get_user_input(prompt)
state, code = SpotifyOAuth.parse_auth_response_url(response)
if self.state is not None and self.state != state:
Expand Down Expand Up @@ -457,12 +455,11 @@ def get_auth_response(self, open_browser=None):
if redirect_port:
return self._get_auth_response_local_server(redirect_port)
else:
logger.warning('Using `%s` as redirect URI without a port. '
'Specify a port (e.g. `%s:8080`) to allow '
logger.warning(f'Using `{redirect_host}` as redirect URI without a port. '
f'Specify a port (e.g. `{redirect_host}:8080`) to allow '
'automatic retrieval of authentication code '
'instead of having to copy and paste '
'the URL your browser is redirected to.',
redirect_host, redirect_host)
'the URL your browser is redirected to.')

return self._get_auth_response_interactive(open_browser=open_browser)

Expand Down Expand Up @@ -511,8 +508,8 @@ def get_access_token(self, code=None, as_dict=True, check_cache=True):
headers = self._make_authorization_headers()

logger.debug(
"sending POST request to %s with Headers: %s and Body: %r",
self.OAUTH_TOKEN_URL, headers, payload
f"Sending POST request to {self.OAUTH_TOKEN_URL} \
with Headers: {headers} and Body: {payload!r}"
)

try:
Expand Down Expand Up @@ -541,8 +538,8 @@ def refresh_access_token(self, refresh_token):
headers = self._make_authorization_headers()

logger.debug(
"sending POST request to %s with Headers: %s and Body: %r",
self.OAUTH_TOKEN_URL, headers, payload
f"Sending POST request to {self.OAUTH_TOKEN_URL} \
with Headers: {headers} and Body: {payload!r}"
)

try:
Expand Down Expand Up @@ -733,9 +730,9 @@ def _open_auth_url(self, state=None):
auth_url = self.get_authorize_url(state)
try:
webbrowser.open(auth_url)
logger.info("Opened %s in your browser", auth_url)
logger.info(f"Opened {auth_url} in your browser")
except webbrowser.Error:
logger.error("Please navigate here: %s", auth_url)
logger.error(f"Please navigate here: {auth_url}")

def _get_auth_response(self, open_browser=None):
logger.info('User authentication requires interaction with your '
Expand All @@ -759,12 +756,11 @@ def _get_auth_response(self, open_browser=None):
if redirect_port:
return self._get_auth_response_local_server(redirect_port)
else:
logger.warning('Using `%s` as redirect URI without a port. '
'Specify a port (e.g. `%s:8080`) to allow '
logger.warning(f'Using `{redirect_host}` as redirect URI without a port. '
f'Specify a port (e.g. `{redirect_host}:8080`) to allow '
'automatic retrieval of authentication code '
'instead of having to copy and paste '
'the URL your browser is redirected to.',
redirect_host, redirect_host)
'the URL your browser is redirected to.')
return self._get_auth_response_interactive(open_browser=open_browser)

def _get_auth_response_local_server(self, redirect_port):
Expand Down Expand Up @@ -868,8 +864,8 @@ def get_access_token(self, code=None, check_cache=True):
headers = {"Content-Type": "application/x-www-form-urlencoded"}

logger.debug(
"sending POST request to %s with Headers: %s and Body: %r",
self.OAUTH_TOKEN_URL, headers, payload
f"Sending POST request to {self.OAUTH_TOKEN_URL} \
with Headers: {headers} and Body: {payload!r}"
)

try:
Expand Down Expand Up @@ -899,8 +895,8 @@ def refresh_access_token(self, refresh_token):
headers = {"Content-Type": "application/x-www-form-urlencoded"}

logger.debug(
"sending POST request to %s with Headers: %s and Body: %r",
self.OAUTH_TOKEN_URL, headers, payload
f"Sending POST request to {self.OAUTH_TOKEN_URL} \
with Headers: {headers} and Body: {payload!r}"
)

try:
Expand Down Expand Up @@ -1152,9 +1148,9 @@ def _open_auth_url(self, state=None):
auth_url = self.get_authorize_url(state)
try:
webbrowser.open(auth_url)
logger.info("Opened %s in your browser", auth_url)
logger.info(f"Opened {auth_url} in your browser")
except webbrowser.Error:
logger.error("Please navigate here: %s", auth_url)
logger.error(f"Please navigate here: {auth_url}")

def get_auth_response(self, state=None):
""" Gets a new auth **token** with user interaction """
Expand Down
1 change: 1 addition & 0 deletions spotipy/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,7 @@ class Retry(urllib3.Retry):
"""
Custom class for printing a warning when a rate/request limit is reached.
"""

def increment(
self,
method: str | None = None,
Expand Down
Loading
Loading