iamogbz
iamogbz

Reputation: 99

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?

Upvotes: 2

Views: 1630

Answers (2)

a_guest
a_guest

Reputation: 36239

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' 

Upvotes: 3

ProfOak
ProfOak

Reputation: 551

A dictionary is probably the easiest way to go.

class Permission(object):
    user = {
        'add': 'add_user',
        'view': 'view_user',
        'edit': 'edit_user',
    }
    tool = {
        'add' : 'add_tool',
        'view' : 'view_tool',
        'edit' : 'edit_tool',
    }

print(Permission.user['view'])
print(Permission.tool['view'])

output:

view_user
view_tool

Upvotes: 0

Related Questions