lk-geimfari / mimesis

Mimesis is a robust data generator for Python that can produce a wide range of fake data in multiple languages.
https://mimesis.name
MIT License
4.34k stars 326 forks source link

A custom handler with an alias returns an error when using the alias #1514

Open mheguy-flo opened 3 months ago

mheguy-flo commented 3 months ago

Bug report

Repro:

field.register_handler("bloop", my_field_handler)
field.aliases.update({"zoop": "bloop"})
field("zoop") # generates error
lk-geimfari commented 3 months ago

I'm not sure aliases make sense for custom fields, since you can already give them any name you want.

lk-geimfari commented 3 months ago

Well, almost any. Most names allowed for aliases aren't allowed for custom fields (like emojis and stuff).

mheguy-flo commented 3 months ago

That makes sense if everything is done statically in code. In my case, things are not static. Here's an example of how I'm using your project:

fieldset = Fieldset()
# file represents an external data source
aliases = json.load(file)
# aliases = { "col 1": "positive_number_under_10"}
fieldset.aliases.update(aliases)
fieldset.register_handlers(
    (
        ("positive_number_under_10", positive_number_under_10),
    )
)
data: dict[str, list[Any]] = {}

# columns comes from a database schema
for col in columns:
    data[col.name] = fieldset(col.name, i=rows_in_table)

Neither the aliases nor the columns are determined before runtime. I cannot register the handlers with the column names as they are generally not valid python identifiers.

My (ugly) workaround currently is to make aliases global and use it in the lookup. But this seems like a needless workaround since it's just duplicating the aliases feature built into mimesis.

You can see in #1515, you can support aliases and custom handlers by moving a single line of code from _lookup_method to perform.

lk-geimfari commented 3 months ago

I see. I'll merge your PR and release new version later this weekend. Thank you!