Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic way to convert the string "None" to a proper None

I could create an if statement, bet there might be a better way.

like image 304
Paul Lernmark Avatar asked Oct 21 '14 08:10

Paul Lernmark


2 Answers

Even more concise,

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

Although evaluating expressions is kinda... eh.

If you're interested, basically, if you use it in production, say on a web server, and someone submits something (in a form, or whatever) that eventually goes through an eval(), they'd essentially have access to a limited version of a python shell with direct write access running on your server.

For instance, depending on what you have imported, even if the eval() in the web server's code doesn't evaluate the submitted text directly, with time, they could figure out how to send through nice things like,

eval(subprocess.call('sudo rm -rf /')), to wipe your server,

eval(sys.exit()) to stop the web server,

and eval(subprocess.call('ls -R -a /')) to list every file on the server, then you could pipe that into a file and use curl to send it to your self.

So, it can be dangerous, to say the least.

like image 163
gucciferXCIV Avatar answered Oct 04 '22 20:10

gucciferXCIV


You could use ast.literal_eval:

In [6]: import ast

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

However, an if-statement or ternary expression would be faster if all you need is to convert 'None' to None:

x = None if x == 'None' else x
like image 34
unutbu Avatar answered Oct 04 '22 20:10

unutbu