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

Question:

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?

Asked By: usustarr

||

Answers:

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'
}
Answered By: Yevhen Kuzmovych

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.

Answered By: Dmitry Nikolaev
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.