usustarr
usustarr

Reputation: 418

How to pass an object as a dictionary key in Python(TestComplete issue?)

I am aware dictionary keys needs to be strings or immutable objects. But I don't want to pass strings as a key. Reason is, every where I use the dictionary, I have to type exact string and leaves so mach hard coding and room for errors.

This is only happening on TestComplete (V12). Is it possible for me to do something like this,

class test():
    testStr = 'test'
    testStr2 = 'test2'

class Coverage():
     Data ={test.testStr    : True,
            test.testStr2   : 'something with white space'}

If this is a bad idea, why?

Upvotes: 0

Views: 1610

Answers (2)

Dmitry Nikolaev
Dmitry Nikolaev

Reputation: 3918

This seems to be a problem in TestComplete's Python parser and SmartBear has a patch for it. You can contact them to get the patch.

Upvotes: 1

Yevhen Kuzmovych
Yevhen Kuzmovych

Reputation: 12140

You can use Enum for this purposes.

from enum import Enum     # for enum34, or the stdlib version
# from aenum import Enum  # for the aenum version
Animal = Enum('Animal', 'ant bee cat dog')

Animal.ant  # returns <Animal.ant: 1>
Animal['ant']  # returns <Animal.ant: 1> (string lookup)
Animal.ant.name  # returns 'ant' (inverse lookup)

or equivalently:

class Animal(Enum):
    ant = 1
    bee = 2
    cat = 3
    dog = 4

data = {
    Animal.ant: 'small',
    Animal.dog: 'big'
}

Upvotes: 1

Related Questions