How do you make a unique map key in Python?
Question: I want to make a map containing various attributes of a single item and share
it across several modules. The most obvious answer is to use a string, but
since the map will be used across several modules, I don't want maintainers to
have to know about all existing attributes. For example, if two modules want
something associated with "color", they shouldn't clobber each other by
accidentally picking the same name.

A few ideas I've thought of which don't work:

1) Strings, integer keys: As said above, this isn't easily extensible.

2) Create of a particular class, use id(): I thought it would work to make a
Key() class, for example, but this doesn't work in the case of modules
imported from two different places. For example, you might want to make the
"color" attribute described above as follows:

    
    
    color = Key()
    

This doesn't work if you do

# module named foo

    
    
    bar = Key()
    import foo
    id(foo.bar) == id(bar)
    

3) Look at the stack trace to see where the Key was created and use that as
part of the identifier. Definitely wouldn't want to use line number, as this
would be too brittle. Using module and name of item fails in the case of the
main module, though. For example:

in foo.py:

    
    
    key = Key() # will be named foo.py-key
    

elsewhere, in bar.py:

    
    
    import foo
    
    foo.key   # will be named /Users/person/foo.py-key
    

Thanks! Any advice is appreciated.


Answer: Use a string, but prefix it with the current module name. Then you won't get
any collisions.

    
    
    key = __name__ + '.color'
    

