1

I referenced the code in this answer about an avatar command for Discord Python bots:

@commands.command()
async def avatar(self, ctx, *,  avamember : discord.Member=None):
    userAvatarUrl = avamember.avatar_url
    await ctx.send(userAvatarUrl)

What is the function of * as its own argument? I expect to see it as *args or **kwargs

Jack Deeth
  • 3,062
  • 3
  • 24
  • 39
glass-ships
  • 53
  • 1
  • 6
  • All arguments to the right of the star must be keyword arguments.[PEP 3102](https://stackoverflow.com/questions/53797057/star-as-an-argument-in-python-function) – Zach Feb 06 '22 at 07:27
  • 2
    [keyword-only arguments](https://www.python.org/dev/peps/pep-0570/#keyword-only-arguments): *"To mark parameters as keyword-only, indicating the parameters must be passed by keyword argument, place an * in the arguments list just before the first keyword-only parameter."* – Ch3steR Feb 06 '22 at 07:28

2 Answers2

1

They are called keyword-only arguments. They restrict all the parameters that come after the * to accept keyword-only arguments.

With your given example:

@commands.command()
async def avatar(self, ctx, *,  avamember : discord.Member=None):
    userAvatarUrl = avamember.avatar_url
    await ctx.send(userAvatarUrl)

If you invoke the avatar function with positional arguments only:

avatar(ctx_value, "member_value")

It will throw an error. TypeError: avatar() takes 1 positional argument but 2 were given.

The function will only accept a positional argument as the first argument, and a keyword-only argument as a second argument. To avoid the error, you must invoke the avatar function with a keyword-only argument as a second argument:

avatar(ctx_value, avamember="member_value")

Note. Am using strings for "member_value" because I don't know the discord.Member type hint. So you must replace it with the appropriate type.

Stanley Ulili
  • 702
  • 5
  • 7
1

What Stanley Ulili said is correct when using basic python, but in the context of discord.py, the meaning of * is a bit different.

* basically means that variable alone will consume the rest of the command parameter. Or else each parameter is limited to only one word unless using quotes. Adding the * here would make !avatar Wasi Master possible for a member with the name Wasi Master. Otherwise it would raise a error saying member "Wasi" not found, since it only accepted the first word as the paremeter avamember and excluded the rest. Using * would make it accept the entire "Wasi Master" as the avamember variable

Wasi Master
  • 1,112
  • 2
  • 11
  • 22