Click here to Skip to main content
15,919,245 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi everyone, I am a starting programmer in python. I have built a script through 'spotipy' that creates a new playlist based on your best listened-to songs. If the playlist already exists you have the option to replace the songs. At the moment the script works, but I know it can be cleaner and more efficient. I used functions for this. I would like to learn how I could make this script more efficient and cleaner, would anyone like to help me? it would be greatly appreciated!

What I have tried:

import spotipy
import spotipy
from spotipy.oauth2 import SpotifyOAuth

sp = spotipy.Spotify(auth_manager=SpotifyOAuth(client_id="",
                                               client_secret="",
                                           redirect_uri="https://google.com",
                                               scope="user-top-read playlist-read-private playlist-modify-private"))

fields = ['rank_position', 'album_type', 'album_name', 'album_id',
          'artist_name', 'artist_id', 'track_duration', 'track_uri',
          'track_name', 'track_popularity', 'track_number', 'track_type']

tracks = {}


def check_exist(playlist_name):
    playlists = sp.current_user_playlists()
    for name in playlists['items']:
        if name['name'] == playlist_name:
            message = input("playlist already exists, replace the songs? y/n: ")
            if message == 'y':
                return True, name['id']
            elif message == 'n':
                print('ok')
    else:
        return False

def list_top_songs():
    n = int(input("how many top songs?: "))
    results = sp.current_user_top_tracks(limit=n)
    for i in fields:
        tracks[i] = []

    for item in results['items']:
        tracks['album_type'].append(item['album']['album_type'])
        tracks['album_id'].append(item['album']['id'])
        tracks['album_name'].append(item['album']['name'])
        tracks['artist_name'].append(item['artists'][0]['name'])
        tracks['artist_id'].append(item['artists'][0]['id'])
        tracks['track_duration'].append(item['duration_ms'])
        tracks['track_uri'].append(item['uri'])
        tracks['track_name'].append(item['name'])
        tracks['track_popularity'].append(item['popularity'])
        tracks['track_number'].append(item['track_number'])
        tracks['track_type'].append(item['type'])
    return tracks['track_uri']


def edit_playlist(playlistid, songs):
    try:
        sp.playlist_replace_items(playlistid, songs)
        print("songs are replaced!")
    except Exception as e:
        return e


def create_playlist(username, playlist_name, public, collaborative, description):
    try:
        result = sp.user_playlist_create(user=username, name=playlist_name, public=public, collaborative=collaborative,
                                         description=description)
        return result['id']
    except Exception as e:
        return e


def add_songs(playlistid, songs):
    try:
        sp.playlist_add_items(playlistid, songs)
        print("songs are added!")
    except Exception as e:
        return e


def user_input():
    playlist_name = input("name of the playlist?: ")
    check = check_exist(playlist_name)
    if check is False:
        username = input("username?: ")
        public = input("public playlist? y/n: ")
        if public == 'y':
            public = True
        else:
            public = False
        collaborative = input("collaborative playlist? y/n: ")
        if collaborative == 'y':
            collaborative = True
        else:
            collaborative = False
        description = input("playlist description: ")
        return username, playlist_name, public, collaborative, description
    else:
        return True, check[1]

def main():
    userinp = user_input()
    if userinp[0] is True:
        songs = list_top_songs()
        existing_id = userinp[1]
        edit_playlist(existing_id, songs)

    else:
        playlist_id = create_playlist(userinp[0], userinp[1], userinp[2], userinp[3], userinp[4])
        songs = list_top_songs()
        add_songs(playlist_id,songs)



if __name__ == '__main__':
    main()
Posted
Updated 12-Sep-22 22:14pm
v2

1 solution

The technique you are looking for is called "refactoring". This is a Quick Answers forum and the topic is much larger than that.

Start by researching "refactoring" - specifically in Python. There are loads of resources ...code refactoring in python - Google Search[^]
 
Share this answer
 
Comments
Member 13554627 13-Sep-22 4:36am    
Thankyou! I will look into it.
CHill60 13-Sep-22 5:58am    
My Pleasure - if anything goes wrong or you get stuck please do post another question and we'll try to help you out with the specifics

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900