Python - Executing a transform function in a dict parameter when creating a new transformdict

I read about this cool new dictionary, transformdict

I want to use it in my project, initializing a new dict file with a regular dict:

tran_d = TransformDict(str.lower, {'A':1, 'B':2}) 

which succeeds, but when I run this:

 tran_d.keys() 

I get:

 ['A', 'B'] 

How would you suggest executing the transform function in the (regular) dict parameter when creating a new dict transform? To be clear, I want the following:

 tran_d.keys() == ['a', 'b'] 
+5
source share
3 answers

I already said this in the comments, but it’s important to understand that this is not what TransformDict should do. Therefore, you can subclass it with a special implementation for keys :

 class MyTransformDict(TransformDict): def keys(self): return map(self.transform_func, super().keys()) 

Depending on your version of Python, you will probably need to use list() around map (Python 3) or provide arguments for super : super(TransformDict, self) (Python 2). But this should illustrate the principle.

As @Rawing noted in the comments, there will be more methods that won't work as expected, i.e. __iter__ , items and probably also __repr__ .

+3
source

In the implementation I saw, the conversion function can be achieved using a property called transform_func , therefore

 list(map(tran_d.transform_func, tran_d.keys())) 

.

+2
source

I would not use TransformDict. It was proposed as PEP 455 and rejected . This means that it will not be a built-in function, so you have to manually implement it yourself or use some library that does this.

The conclusions of the BDFL delegates about PEP can be found here . Truncated version:

  • This is less readable than key conversion before use.
  • It is oddly strange that sometimes even emit the wrong mistakes.
  • It introduces unnecessary complexity, since using simple dicts avoids problems.
0
source

Source: https://habr.com/ru/post/1269649/


All Articles