0

I have some puzzling code I am trying to migrate to Typescript. Look at this:

    def add_Octopus(self, code, cracker, fate, description, arm_number, ink_content, fate_pointer, churlishness=None):
    self.special_octopoda[
        Octopus(code, description, arm_number, fate, churlishness, self, ink_content, fate_pointer)] = fate_pointer, cracker

It looks to me as though the Octopus object is being used as a key in a dictionary named special_octopoda. Is that allowed in Python? It certainly isn't in Typescript/Javascript.

Gus Mueller
  • 185
  • 10
  • only restriction is that the key must be immutable and hashable – EdChum Dec 13 '18 at 14:15
  • Dictionary keys must be hashable - you can not use mutable objects. On custom classes you can create the needed methods to allow them to be used as keys. – Patrick Artner Dec 13 '18 at 14:16

2 Answers2

1

Yes, you can use any immutable object as a key in a Python dictionary.

The Octopus class must, in some way, create immutable instances. It might, for example, be a subclass of tuple or use __slots__ to do that.

meatballs
  • 3,917
  • 1
  • 15
  • 19
0

Only immutable types can be used as key in python. For a possible workaround wrap it in as a tuple:

self.special_octopoda(<something>, Octopus(...))

or make your class hashable:

class Octopus:
    def __hash__(self):
        # hash implementation
  • no workaround needed - the thing _is_ working, just not in TS – Patrick Artner Dec 13 '18 at 14:17
  • Workaround is needed! You have to wrap it into a tuple or the class should implement the `__hash__` – Attila Bognár Dec 13 '18 at 14:22
  • He _has_ code that works in python where it _uses_ the Octopus Instance as key - he tries to convert to TypeScript. ergo: no workaround needed... unless you provide a TypeScript-Workaround - because he can not do this in TS – Patrick Artner Dec 13 '18 at 14:25
  • @PatrickArtner the question was `In Python, can an object be used as a key in a dictionary?` not how to do it in TS. And you can't use any object as a key in python... – Attila Bognár Dec 13 '18 at 15:05
  • Look at the question. `I have code like this .... ` .. followed by code using an instance as key in a dict followed by `it looks to me as though the Octopus object is being used as a key in a dictionary named special_octopoda. Is that allowed in Python? It certainly isn't in Typescript/Javascript.` He **has** code that is using an instance of an object in python ... this code's class must already be hashable for the code to work. There is no workaround needed. He is puzzled by this because he is translating to TS where this is NOT possible. – Patrick Artner Dec 13 '18 at 17:22