Python eval() exception handling in one line [closed] - python

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
I am programming an IRC bot in python. All code is in one line. I know that this is not how python programs should be written, but this is experimental. I want to execute oneliner scripts from IRC, but I don't know how to handle exceptions.
Is it possible to evaluate a python expression and handle possible exceptions in one line? AFAIK try-except does not work in one line.
Here is the current code: http://pastebin.com/f34brq91.
It is not very easy to read that, but it is not necessary to understand it to answer my question. :)

No, there is no way to put an exception handler in one line. You can only put simple statements on one line, and try - except is a compound statement.
There are also no functions that'll swallow exception for you.
The only way you'd be able to pull something like this off in one line, is to create a new code object from raw bytes that define the bytecodes for a blanket try - except: pass construct. Using that bytecode you would then go on to create a function that swallows exceptions.
However, I am not going to write one for you. Sorry.

Related

Is it possible to make key words in python [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I was wondering if it was possible to make a keyword similar to 'and', or if it is part of the python compiler?
Thx
You can file a PEP (although good luck getting your new keyword accepted); or you can implement it yourself. Other than that, no: python doesn't allow dynamic syntax.
What you can do is look at the magic methods which are called by operators. Redefining these is sometimes handy. Pathlib makes it possible to do this:
from pathlib import Path
Path("a/b") / "c/d.txt"
And they didn't have to introduce any new operators or keywords, even though the usual meaning of / is division, not concatenation.

How to a create a random Python program generator? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
Don't ask why, but I want to create a Python program that generates a random Python program that is valid for execution. I found a similar thread Searching for a random python program generator , but it's old and all the links except the demonstration http://www.4geeks.de/cgi-bin/webgen.py are dead. And maybe something has changed in these years and it's easier to do such thing?
One of idea is to use quantum collapse algorithm/technique. This would require to make a kind of database, where I describe what symbols can came after previous one. For example after a can come (,, any letter, etc, but never, for example, ). Still I think this will create very gibberish source and I could easily set wrong conditions.
There are two main ways to achieve this:
Use third parties to generate runnable junk code, for instance using yarpgen to generate a valid C program, and then using things to translate that to python like https://github.com/DAN-329/C_to_Python_translator
Write a python code that writes randomly generated functions with random parameters calling eachother, if you just need a bunch of functions calling eachother doing random math operations that should not be that hard to implement.

How does Python interpret its code? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am currently trying to learn Python. I have learned some Liberty Basic and wanted to know how Python interprets its code. I have noticed with some of my small programs that it runs it in a strange way, and I am not sure how it runs it. In Liberty Basic, it goes from top to bottom. Before I get into any major Python programming, I would like to know how it runs its code. Top to bottom, bottom to top? Any information relating to this would be appreciated.
Python interprets any given code file top-to-bottom. However, there are many ways that code that be interpreted top-to-bottom but not run in exactly that way.
For instance, consider the following small program:
def foo():
print("World")
print("Hello")
foo()
If you were looking at only the ordering of the print() calls in the file, you might expect that the output would be
World
Hello
But, because the first print statement is inside a function definition, it isn't run immediately when the interpreter gets to that line - instead, it's made part of the foo function. Later on, when the foo() call is made, is when it is actually run, and thus the actual output is...
Hello
World
Have you considered reading any book about Python programming? Here's a list of good reads: http://docs.python-guide.org/en/latest/intro/learning/
Python starts executing code line by line from top to bottom, and branches on branching conditions like any other imperative programming language. This shouldn't be too far removed from Basic...

Exit in a function using Python [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
A quick function question in Python. Is it possible to stop a function from processing and return early. i.e like this:
def _do_something():
if not exists('/etc/', use_sudo=True):
# no files don't do any more
return
# if ok continue with stuff
sudo('/etc/init.d/nginx stop')
Is this ok? Or is there something like 'exit' ?
Your question sounds like " is there a better way to do this?".
no, that looks fine and will work.
For loops you could use the break-statement, but in a function this is good way to "stop" it - returning None implicitly.
Yes, this is a common way of structuring program logic.
Some people would argue that you write your function the other way around, like:
def _do_something():
if exists('/etc/', use_sudo=True):
sudo('/etc/init.d/nginx stop')
because it is shorter and, in a way, more directly represents what you mean by writing the function.
One thing to worry about with the structure that you have in your question is what happens when the function becomes more complicated. It is possible for a large and complicated function with many return statements to actually have unreachable code, where the function is guaranteed to return early and there is code at the end of the function that will not be executed.
def lol():
print "first!"
return
print "unreachable"
In this case, it is trivial to see that "unreachable" will never be printed, but if you have many nested if/else statements, this becomes less obvious. Good IDEs will warn you about unreachable code, but this is something to consider if you choose to program in a simpler text editor.
Side note: Just in case you weren't aware, Python functions that start with one or two underscores often have a "special meaning" attached to them. I'll leave the rest for you to explore.

Python: Is exec always bad practice and if so why not deprecated [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Can someone think of an example with good practice that uses exec?
If there is always a more efficient and secure way to replace exec, why python doesn't deprecate exec?
As explained in other questions, eval/exec are considered bad practice because they're generally abused to do a task where they aren't needed, leading to potential security issues and generally bad programming.
There are, however, valid uses for these mechanisms, and they expose important functionality that is not available elsewhere - executing arbitrary code at runtime.
Imagine, for example, that you want write a application that updates itself. You could fetch a script from a remote URL that runs with exec and updates your application to the latest version. While doing something like that, by itself, would pose a great security hazard, it's not hard to make the process secure through the use of digital signatures.
You can find another common use in the code module source: executing code input from the user at runtime for debugging purposes.
No, eval and related tools are not always bad by any measure.
There are a number of things that only work well when they are expressed as regular functions with regular, positional or keyword arguments (not magic *args or **keywords args). There's no way to dynamically create a function with a desired set of arguments, except with eval.
For a good example of how this can be used, examine the implementation of collections.namedtuple. Although it would be possible to create a class factory like that without eval, but all of the functions it defines, __new__ and _replace in particular, would have useless help text, and would be a less convenient tool without it. Worse, the non-eval implementation would almost certainly be SLOWER.
Another, more sweeping example of this exact use of eval is the fine decorator library, which generalizes this practice in a collection of tools that allow you to dynamically create functions with particular function signatures; it uses eval internally.

Categories