How to efficiently overwrite a variable value if present in configuration dictionary?

59 Views Asked by At

I have a simple piece of code that works, but I'd like to know if I can make it more Pythonic by using the dict.get() method.

chunk_size = 100000
if "chunk_size" in self.conf["source_config"]:
    chunk_size = self.conf["source_config"]["chunk_size"] 

This overwrites the value for variable chunk_size with self.conf["source_config"]["chunk_size"], but only if the key chunk_size is present in said configuration.

How can I make this more Pythonic?

2

There are 2 best solutions below

7
Klops On

This is one possible way you might or might not have thought about;

chunk_size = 100000
conf = {}

chunk_size = conf["chunk_size"] if "chunk_size" in conf else chunk_size

This might be a little more pythonic than a full if clause?

0
Joep On

Based on the answers of @h4z3 and @buran it appears to use .get() and use a default value. This looks like the following:

chunk_size = self.conf["source_config"].get("chunk_size", 100000)