Skip to content Skip to sidebar Skip to footer

Is It A Best Practice To Use Python Ast Library For Operations Like Converting String To Dict

I have been trying to convert a string of dictionary objects as given below '{'Cmd': None, 'Hostname': None, 'Entrypoint': None, 'Env': None, 'OpenStdin': False, 'Tty': False,

Solution 1:

But is ast library is built indented to solve problems like this ?

Your concern is valid. ast.literal_eval, just as the normal eval, were not primarily designed to deserialize data. And that's because Python code was never designed to serialize data in the first place.

But there isn't really anything exotic about it: under the hood, it uses the interpreter's built-in compile() (which is the same function CPython uses to parse normal code), but literal_eval will also generate and go through the AST, and will raise an exception if it contains anything other than literals.

In practice, there are two issues to you need to think about: security & performance. For the example you posted, performance shouldn't be much of an issue, so you should stick with ast.literal_eval (which is thought to be quite secure so far). If you're dealing with (much) larger dictionaries, however, then you're likely to approach some memory issues.

In that case and if possible, the saner choice by far would be to avoid serializing the data as Python code in the first place and use something like JSON. If not, consider converting the string to some other form before parsing it; you could, for example, use a regex to convert it to JSON first (the format is very similar) and then parse it with json.loads. But as long as you're not having performance issues, stick with ast.literal_eval and you should be fine.

In any case, no matter what you do, never, never use eval. It just leaves a gaping security hole for only a marginal benefit.

Post a Comment for "Is It A Best Practice To Use Python Ast Library For Operations Like Converting String To Dict"