0

I would like to import some functions from another cog so they can be used for several cogs in different .py files. How would I go about doing that? Here's what the documentation says:

class Economy(commands.Cog):
    ...

    async def withdraw_money(self, member, money):
        # implementation here
        ...

    async def deposit_money(self, member, money):
        # implementation here
        ...

class Gambling(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    def coinflip(self):
        return random.randint(0, 1)

    @commands.command()
    async def gamble(self, ctx, money: int):
        """Gambles some money."""
        economy = self.bot.get_cog('Economy')
        if economy is not None:
            await economy.withdraw_money(ctx.author, money)
            if self.coinflip() == 1:
                await economy.deposit_money(ctx.author, money * 1.5)

as an example, but that means I have to define economy every time if I would like to call on it. Is there a more efficient method for calling a function in another cog?

Harmon758
  • 5,084
  • 3
  • 22
  • 39
Lego490
  • 135
  • 1
  • 12
  • Assuming the file is called `cog.py`, you can try using `from cog import Economy` in the file you want to use `Economy` again – Benjin Jan 27 '20 at 07:43
  • The file isn't named cog.py, it's in a folder called cogs, structured like this: main.py cogs -> cog files here – Lego490 Jan 27 '20 at 07:51
  • Try this: https://stackoverflow.com/questions/1260792/import-a-file-from-a-subdirectory with the above – Benjin Jan 27 '20 at 07:54
  • Importing `Economy` itself won't work as is, since `withdraw_money` and `deposit_money` are instance methods, and initializing another version of the cog would definitely be a lot less efficient than simply getting the existing one with `Bot.get_cog`. – Harmon758 Jan 27 '20 at 08:07
  • 1
    You could try setting `economy` in `Gambling.__init__`. That would make the order in which you load cogs meaningful, and you would need to add logic to handle reloads if that's possible in your code. – Patrick Haugh Jan 27 '20 at 15:04

1 Answers1

1

If withdraw_money and deposit_money don't use any of Economy's attributes or methods, you could make them static methods and import Economy to use them or just make them functions outside the class/cog and import them directly.

Otherwise, you can look for a way to refactor those methods so that they don't rely on Economy so that you can make them static methods or independent functions.

If that's not possible, this is already the best way to do it.
Bot.get_cog is O(1) anyway, so there's very minimal impact efficiency-wise.

Harmon758
  • 5,084
  • 3
  • 22
  • 39