Skip to content

Custom Type Resolver #93

Description

@PenguinBoi12

Argument parsing in Command._convert_type currently supports only types whose constructor accepts a raw string (int("6"), float("3.14")). There is no way to teach the framework how to parse a complex object, such as a User looked up by display name, without monkey-patching the command internals.

The idea is to let any class act as a type resolver by implementing a resolve classmethod. The argument parser detects this interface via duck typing and delegates to it instead of calling the constructor directly. An optional registration helper on Bot could cover types you don't own.

Proposed API

class User:
    @classmethod
    def resolve(cls, value: str) -> Self:
        return ... # build user from value

@bot.command()
async def profile(ctx, user: User):
    await ctx.reply(f"Power level: {user.power_level}")
# For types you don't own
@bot.type_resolver(Color)
def parse_color(value: str) -> Color:
    return Color.from_hex(value)

The hook sits in Command._convert_type. The resolver lookup order should be: explicit registry on Bot first, then the resolve classmethod, then the bare constructor, then a passthrough to str. Error handling is needed, a resolve that raises should probably surface as a BadArgumentError rather than silently falling back to the raw string.

Metadata

Metadata

Assignees

Labels

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions