1

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
Flame of udun
  • 2,136
  • 7
  • 35
  • 79
  • 7
    This is very, very bad code. Don't try to learn from it. – Oleh Prypin Aug 23 '13 at 19:00
  • may be you can ask on http://codereview.stackexchange.com –  Aug 23 '13 at 19:01
  • 1
    I actually cringed. I don't cringe at code often. – roippi Aug 23 '13 at 19:03
  • This should have been `int(s, 16)` (and the parameter should have been called something other than `str`). – user2357112 Aug 23 '13 at 19:03
  • @OlehPrypin Could you please explain what makes this code so bad. I am only a beginner so can't evaluate it. – Flame of udun Aug 23 '13 at 19:04
  • 1
    This code is bad for many reasons: 1) it overrides the `str` built-in inside the function. 2) the empty `{}`'s do absolutely nothing 3) `eval` will run any code you put in it (VERY dangerous) 4) the same thing can be accomplished by just doing `int(s, 16)`, where `s` is the string 5) it will blow up if you put in anything other than a string. –  Aug 23 '13 at 19:08

1 Answers1

4

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.

agf
  • 171,228
  • 44
  • 289
  • 238
  • Oh okay..This does answer why the code is a no-no...but how is the hex value converted into an integer value? – Flame of udun Aug 23 '13 at 19:09
  • 1
    @JaneLove Because Python recognizes `0xaf` as valid Python code, and runs it. Try typing that into the Python interpreter -- you'll get an integer as the output. – agf Aug 23 '13 at 19:10