How does the following code snippet work?

283 Views Asked by At

I am a novice in python and am going through an opensource project called pyOBD by Donour Sizemore for the ELM327(not really sure,could be aimed at more scantool devices).I can make out that the following is a method to convert a hex value to int.But how does it work? Specially the line with eval in it.

 def hex_to_int(str):
     i = eval("0x" + str, {}, {})
     return i
1

There are 1 best solutions below

2
On BEST ANSWER

eval runs a string as if it were Python code, and then outputs the result.

In this case, it runs something like 0xaf, which is a way of specifying a hexadecimal literal, and outputs the resulting integer. Try typing 0xaf into the Python interpreter, and you'll get an integer as the result.

eval is not safe to use on untrusted input. For example,

eval("0xa and __import__('os').remove('some/file/path')")

could delete a file on your system.

It would be better to use ast.literal_eval or int:

>>> import ast
>>> ast.literal_eval("0xaf")
175
>>> int("af", 16)
175

Which are safe and produce the same result.