Search code examples
pythonfunctionarguments

python - How do I define arguments in a function that are optional


I have this code:

async def send_log(title: str, guild: discord.Guild, description: str, color: discord.Color, file: discord.File):
  log_channel = guild.get_channel(1083504881744224367)
  embed = discord.Embed(
    title=title,
    description=description,
    color=color,
    file=file
  )

but I want the file: discord.File argument to be optional because I call this function multiple times and I only want to file option once.

I know its possible, but I don't know how to do it. Could someone tell me?


Solution

  • It is sounding like you want to pass the argument once and then invoke the function multiple times with the same argument.

    One option for doing that is to have a function that returns the log sending function.

    def send_log_setup(guild: discord.Guild):
        async def send_log(title: str, description: str, color: discord.Color, file: discord.File):
            log_channel = guild.get_channel(1083504881744224367)
            embed = discord.Embed(
                title=title,
                description=description,
                color=color,
                file=file
            )
        return send_log
    
    
    log_sender_for_guild = send_log_setup(guild)
    
    log_sender_for_guild(title, description, color, file)
    

    You can then call log_sender_for_guild and it will always use the same guild that you initially passed in when setting up the function.