Search code examples
javapythonconstants

How to define nested class constants?


I have these constants defined in constants.py

PERMISSION_USER_ADD = 'add_user'
PERMISSION_USER_VIEW = 'view_user'
PERMISSION_USER_EDIT = 'edit_user'
PERMISSION_TOOL_ADD = 'add_tool'
PERMISSION_TOOL_VIEW = 'view_tool'
PERMISSION_TOOL_EDIT = 'edit_tool'

But I do not want to have to type these full constant names out every time I need to add another one.

Coming from Java I could do this.

class Permission {
    class User {
        const ADD = 'add_user';
        const VIEW = 'view_user';
        const EDIT = 'edit_user';
    }
    class Tool {
        const ADD = 'add_tool';
        const VIEW = 'view_tool';
        const EDIT = 'edit_tool';
    }
}

But all python linters flag this as bad coding practice and searching for the python way to do it hasn't been fruitful so far.

So my question is: What's the pythonic way to define nested constants, in a way that supports easy refactoring?


Solution

  • You can use argparse.Namespace which let's you access the members just as for your class example:

    from argparse import Namespace
    
    permissions = Namespace(
        user = Namespace(add = 'add_user', view = 'view_user', edit = 'edit_tool'),
        tool = Namespace(add = 'add_tool', view = 'view_tool', edit = 'edit_tool'),
    )
    

    And then:

    >>> permissions.user.add
    'add_user'