17

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

Abdulrahman Bres
  • 2,603
  • 1
  • 20
  • 39
Paul Lernmark
  • 581
  • 1
  • 6
  • 17
  • Where exactly is the string coming from, and why isn't it already just the `None` object instead? What are you really trying to do? If, for example, you want to save Python data to a file and read it later, there may be better options than whatever it is you're trying to put together. – Karl Knechtel Oct 21 '14 at 08:36
  • Well, I know it might sound strange. In short I'm reading data from a URL and need to convert the parameters with the value None to an actual NoneType. I'm sure there might be better ways to do that, but those parts are out of my control. – Paul Lernmark Oct 21 '14 at 20:29

2 Answers2

39

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
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
10

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.

gucciferXCIV
  • 498
  • 5
  • 11
  • Yeah, in this case I'm reading a third-party-API, so it might be dangerous. But in other cases it might be useful. Thanks! – Paul Lernmark Dec 15 '17 at 10:20