Search code examples
pythonpython-3.xtelegram-botdrypython-telegram-bot

How can i DRY this pycode


i have just started learning python i created this function but as you can see inside the "if" statement i have duplicated the code i have only changed file_id = filename.photo[-1].file_id to file_id = filename.video.file_id to make the function work and it works, but how can i shorten this code

Thank you for your time

def create_post(filename):
    if filename.content_type == 'photo':
        file_id = filename.photo[-1].file_id
        file = bot.get_file(file_id)
        downloaded_file = bot.download_file(file.file_path)
        with open("image.jpg", 'wb') as new_file:
            new_file.write(downloaded_file)
        image = 'image.jpg'
        token = store_file_temporary(image)
        headers = {
            "content-type": "multipart/form-data",
            "Accept": "application/json",
            "Content-Type": "application/json"
        }
        filesd = {
            "title": randomString(),
            "safety": 'safe',
            "contentToken": token
        }
        r = requests.post(url=url + "/posts/", json=filesd, auth=(username, password),
                          headers=headers)
        print(r.json())
        return r.json()
    elif filename.content_type == 'video':
        file_id = filename.video.file_id
        file = bot.get_file(file_id)
        downloaded_file = bot.download_file(file.file_path)
        with open("image.jpg", 'wb') as new_file:
            new_file.write(downloaded_file)
        image = 'image.jpg'
        token = store_file_temporary(image)
        headers = {
            "content-type": "multipart/form-data",
            "Accept": "application/json",
            "Content-Type": "application/json"
        }
        filesd = {
            "title": randomString(),
            "safety": 'safe',
            "contentToken": token
        }
        r = requests.post(url=url + "/posts/", json=filesd, auth=(username, password),
                          headers=headers)
        print(r.json())
        return r.json()

Solution

  • Once you get the file_id = filename.photo[-1].file_id it is basically just exactly same processing from there. So just put this line into if else and for rest of them put a method.

    if filename.content_type == 'photo':
            file_id = filename.photo[-1].file_id
    elif filename.content_type == 'video':
            file_id = filename.video.file_id
    //call some method with file_id where you do the rest of the work.
    somemeaningful_function_name(file_id)
    
    
    def somemeaningful_function_name(file_id):
        //work with file_id
    

    You yourself said about DRY principle. When approaching things like this just go for finding the repeating portion. As a thumb rule, if you are reusing same code block multiple times just put it in a function and use it.