G
G
Goshujin2022-04-21 15:33:00
Python
Goshujin, 2022-04-21 15:33:00

How to get command context without passing it to parameters?

There is a function to send a response:

async def Reply(ctx, text):
    toSend = f"{ctx.author.mention} {text}"
    await ctx.send(toSend)

Which can be used after the completion of any command with the output of some message:
@client.command()
async def test(ctx, text):
    ...
    await Reply(ctx, text)

So, is there any way to call Reply() without passing ctx as a parameter?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Nesterov, 2022-04-21
@AlexNest

Well, in theory it is possible (for example, through global), but without a very strong need for that - it’s not worth it, because:

  • Explicit is better than implicit.
  • Simple is better than complex.

© Zen Python
Not that it is necessary to follow the Zen unquestioningly, but here are more practical considerations:
1. Suppose now you write the necessary commands with Reply using global to get ctx, i. without explicitly specifying the ctx parameter. Let's say it even works. After some time, you will want to add new features. But the more time passes since you originally wrote it, the more likely you are to forget how your code works. At least, it will be quite difficult to immediately remember how this or that function works under the hood. And if ctx is specified as a function parameter, then it will be possible to understand that it needs to be inserted when calling the function from three places, not counting the function code itself:
  • a listing of existing commands that you are likely to look at first and clearly see that ctx is being passed;
  • from the error text if you forget to pass a parameter
  • from hints of any normal ide.

2.At least for me, a function using parameters instead of global variables is easier. And, as a result, it is easier to read.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question