#how to access var inside a decorator that i passed inside __init__

23 messages · Page 1 of 1 (latest)

little fox
#

my code is similar to this : ```py
class SomeView(discord.ui.View):
def init(self, ctx, test: str) -> None:
super().init()
self.ctx = ctx
self.test = test

@discord.ui.button(label=f'Yes, {self.test}') # Error Here
async def callback(self, interaction: discord.Interaction, button: discord.ui.Button) -> None:
    ...``` and i need to access `test` that i passed
west lake
#

Do you mean you want to access test from inside of callback?

little fox
#

sorry i meant to put that in the message

fallow hollow
#
class MyClass:
  def __init__(self, my_var):
    self.my_var = my_var

  @decorator_function(my_var)
  def my_method(self):
    # Use self.my_var inside the decorator
    ...
little fox
#

"test is not defined"

west lake
# little fox no, inside of the decorator for callback

You can't.

Two things are happening at different times.

  1. The class itself is being created. This is when the functions are stored in memory and decorators are called.
  2. An instance of the class is being created. This is when __init__ is called and you create your self.test attribute of the instance.

Here's an example showing the order in which the code runs.

#

!exec ```py
print("Starting demo")

def decorator(func):
print("The decorator is being run")
return func

class Example:
def init(self):
print("The init has run")

@decorator
def function(self):
    ...

print("Creating an instance of Example")
instance = Example()

rain kestrelBOT
west lake
#

Notice the decorator runs before the print after the class is run and before the print in the __init__.

#

So when you pass a parameter to a class to create an instance, all the decorators have already run.

#

You could look at what the discord.ui.button decorator does and do that yourself in __init__, that would let you make the changes you need and you'd have access to test.

little fox
#

Yeah i thought of subclassing discord.ui.Button instead of discord.ui.View last night and my bot runs with no errors, just time to test now

#

await ctx.send()'s view arg requires a discord.ui.View class so i just made one inside the __init__ did self.add_item(ButtonClass(...)) and it works, apart from one thing

#
Traceback (most recent call last):
  File "C:\Users\tesco meal deal\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ui\view.py", line 425, in _scheduled_task
    await item.callback(interaction)
TypeError: callback() missing 1 required positional argument: 'button'
west lake
#

The callback is the function you applied the decorator to. So you'll need to pass the reference to the button as a second parameter.

little fox
#

yeah i got it now, thanks

#

can i close this thing using a command or do i have to do it manually?

#

?solved

#

!solved

#

maybe thats in another bot

west lake
#

Right now you'll need to do it manually

#

I'll add commands eventually