19

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

2
  • 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. Commented Oct 21, 2014 at 8: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. Commented Oct 21, 2014 at 20:29

2 Answers 2

40

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
Sign up to request clarification or add additional context in comments.

1 Comment

@unutbu, you just made my day with: x = None if x == 'None' else x.
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.

1 Comment

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!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.