Opinion on best practice...

Steven D'Aprano steve+comp.lang.python at pearwood.info
Thu Feb 7 23:49:02 CET 2013


Chris Angelico wrote:

> On Thu, Feb 7, 2013 at 5:50 PM, Steven D'Aprano
> <steve+comp.lang.python at pearwood.info> wrote:
>> On Thu, 07 Feb 2013 16:28:17 +1100, Chris Angelico wrote:
>>
>>> You misunderstand. It's actually a very simple rule. Python follows C's
>>> principle of accepting that any return value from an expression should
>>> be ignored if you don't do anything with it.
>>
>> Return values are safe. They don't do anything, since they are *being
>> ignored*, not being executed as code. You have to explicitly choose to do
>> something with the return value before it does anything.
>>
>> If C said "if you don't do anything with the return result of an
>> expression, execute it as code in the shell", would you consider that a
>> desirable principle to follow?
>>
>> def oh_my_stars_and_garters():
>>     return "rm -rf /"
>>
>> oh_my_stars_and_garters()
> 
> Naming a function is safe, too.
> 
> def earth_shattering():
>     os.system("rm -rf /")
> 
> earth_shattering;
> 
> But putting parentheses after it suddenly makes it dangerous. Wow!

Yes, that is correct. Because now you are executing code, which could do
something, and some things are dangerous. But Python will never execute
code unless you explicitly tell it to. There's no concept in Python of
falling back onto code execution if parsing fails.


> Python's pretty risky, right?

Not really, because Python never executes anything you don't tell it to.

But on the other hand, compared to the sandboxing capabilities of Java and
Javascript, Python *is* pretty risky. Hell, we known how risky Javascript
and Actionscript are (Flash vulnerabilities are now the number 1 source of
malware, or so I understand), and they're designed to run in a secure
sandbox. Python isn't. Some rather innocent-looking things *could* involve
code execution (e.g. imports, attribute access). But given the assumption
that you know what you're doing, and you don't eval() or exec() untrusted
strings, Python never executes code *by mistake*.

You might write the wrong code (you can do that in any language) but Python
will never cause something to be executed *because it can't parse it*. If
something doesn't parse, you get a syntax error.


> In REXX, you simply don't *do* that sort of thing. (You'd use the CALL
> statement, for instance.)

Well, Dennis claims that he *does* do it, and that it is one of the better
features of REXX. And in the code snippet you published earlier, I saw
plenty of code intended for the shell, but no CALL statement in sight.

I note that you ignored my question. If REXX reaches code that fails to
parse, does it send it to the shell to be executed by default? If the
answer was No, I expect you would have said so.


-- 
Steven




More information about the Python-list mailing list