Is there an easy way to convert the string "No" to the correct None variable in python?

I could create an if statement, the bet could be better.

+3


source to share


2 answers


You can use ast.literal_eval

:

In [6]: import ast

In [7]: ast.literal_eval('None') is None
Out[7]: True

      



However a 3D expression if-statement

or will be faster if you only need to convert 'None'

to None

:

x = None if x == 'None' else x

      

+12


source


Even more concise,

>>> type(eval('None'))
<class 'NoneType'>

      

Although evaluating expressions is kinda ... eh .

If you're interested, basically if you're using it in production, say a webserver, and someone feeds something (in a form or whatever) that ends up going through eval (), they is essentially access to a limited version of the python shell with direct write access running on your server.

For example, depending on what you imported, even if eval () in the web server code does not evaluate the presented text directly, over time they might figure out how to send via nice things like



eval(subprocess.call('sudo rm -rf /'))

to erase your server,

eval(sys.exit())

to stop the web server,

and eval(subprocess.call('ls -R -a /'))

to list each file on the server, then you can transfer it to a file and use curl to send it to yourself.

So it can be dangerous to say the least.

+1


source







All Articles