question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Choice Fields (Or Enum equivalent) refactors

See original GitHub issue

I am working on Issue #291 . I cant help but notice the code snippets like if conference.status != 1: from junction/proposals/views.py (It might be in some other places too). It is not immediately apparent what 1 represents. I have to open junction/base/constants.py to cross-reference with the file and understand what it is.

So I am raising an Issue here to propose a refactor. To deal with choices field I wrote a handy decorator. It goes something like this:

import inspect


def user_attributes(cls):
    defaults = dir(type('defaults', (object,), {}))  # gives all inbuilt attrs
    return [
        item[0] for item in inspect.getmembers(cls) if item[0] not in defaults]


def choices(cls):
    """
    Decorator to set `CHOICES` attribute
    """
    _choices = []
    for attr in user_attributes(cls):
        val = getattr(cls, attr)
        _choices.append((val, attr))
    setattr(cls, 'CHOICES', tuple(_choices))
    return cls


@choices
class FooEnum:
    FOO = 1
    BAR = 2

print FooEnum.CHOICES  # Will contain `((2, 'BAR'), (1, 'FOO'))`

I also understand we might need some custom get_<choice_field>_display messages. For that I think we can tweak the choices decorator to do the same. That will be something like this.

import inspect


def user_attributes(cls):
    defaults = dir(type('defaults', (object,), {}))  # gives all inbuilt attrs
    return [
        item[0] for item in inspect.getmembers(cls) if item[0] not in defaults]


def choices(cls):
    """
    Decorator to set `CHOICES` and other attributes
    """
    _choices = []
    for attr in user_attributes(cls):
        val = getattr(cls, attr)
        setattr(cls, attr[1:], val[0])
        _choices.append((val[0], val[1]))
    setattr(cls, 'CHOICES', tuple(_choices))
    return cls


@choices
class FooEnum:
    _FOO = [1, "Some Foo String"]
    _BAR = [2, "Some Bar String"]

print FooEnum.CHOICES  # ((2, 'Some Bar String'), (1, 'Some Foo String'))
print FooEnum.FOO  # 1

So we could do something like if conference.status != ConferenceStatus.ACCEPTING_CFP: which makes code base A bit readable and pragmatic.

Any thoughts @kracekumar ?

Issue Analytics

  • State:closed
  • Created 8 years ago
  • Comments:5 (4 by maintainers)

github_iconTop GitHub Comments

1reaction
kracekumarcommented, Nov 26, 2015

@dhilipsiva Sure, but one feature which will be useful is reverse lookup. If choice Public is 1, db contains 1, while returning the data via api, field need to bare the value as Public not 1.

0reactions
dhilipsivacommented, Nov 26, 2015

@kracekumar I created a stand alone decorator for doing this dhilipsiva/orm-choices. Would it be okay if I refactored this code to use the orm-choices library and send a PR?

Read more comments on GitHub >

github_iconTop Results From Across the Web

Huge if statement, refactor using Enum or Map? - Stack Overflow
I changed that into an enum that takes a String (the field name) and a ... So I am thinking the Map might...
Read more >
Make conscious choice when using Enums for persistence ...
Enums are quite good when you want to be treated them as constants in the code, but when an Enum value gets persisted...
Read more >
Enum Mappings with Hibernate - The Complete Guide
In this article, I will show you how to use all 3 of these options to map the following Rating enum. It's used...
Read more >
Using Enum in Symfony - ITNEXT
Here we use a string backed enum, add a field in the Post class. #[Column(type: "string", enumType: Status::class)] private Status $status;. Note, set...
Read more >
When are enums NOT a code smell?
IMHO, when transmitting data using enums to indicate that a field can have a value from a restricted (seldom changing) set of values...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found