Exit in a function using Python [closed] - python

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.

Related

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.

When to use "shortcuts": list comprehensions, generator expressions, lambda functions? [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 2 years ago.
Improve this question
I'm starting to work and getting more familiar with Python in the context of data analytics and just got to know about list comprehensions which I find really elegant.
Although I'm aware there ist the risk of falling into love with it too much at the cost of readabilty, I really didn't find any guidelines or rules of thumb of when or when not to use it.
In my own code I used this generator expression inside a recursive function
--> find_children() is a user definded function to create hierarchical data
(find_children(ancestor) for ancestor in parents if len(parents) > 0)
instead of
if len(parents) > 0:
for ancestor in parents:
find_children(ancestor)
It looks more neat but that's actually the only reason for me.
So I would like to collect opinions of maybe some experienced Pythonistas and their approach regarding this or what best practice is.
List comprehensions are idiomatic python code and as such perfectly fine. Their main competitor is a functional style using map(), filter() etc. Both style are perfectly fine. I would probably refrain from using list comprehensions when you have long statements, e.g.
x["data"]["data"]["data"] for x in something] asks for trouble.
Also nested list comprehensions are evil, I personally see them as a code smell due to their poor readability.
Finally, the goal of good code is to be readable - when you finished a piece of code, step back and try to judge who readable your code really is. Introduce functions and variables to increase readability. List comprehensions are just a part of that picture.

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...

How to make a function do reverse of its job 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
How do you make a function do reverse of what it was programmed to do in Python without reprogramming the entire function?
For example:
swap1 = "abc"
swap2 = "def"
def swap():
global swap1, swap2
swap1 = swap2
into
swap1 = "abc"
swap2 = "def"
def swap():
global swap1, swap2
swap2 = swap1
Any help is appreciated.
A function can only do what it's designed to do. While some functions, by design, are reversible, there is no way to create a general case reverse function. Furthermore, many functions (notably hash functions) are intentionally designed to not be reversible, either simply because information is lost along the way, or because it is intentionally computationally impossible to reverse.
You would do better to rethink your design here - the pattern you demonstrated above using globals is highly undesirable, it will lead to very complex, difficult to maintain or understand code.
in general there is no such way to do this. the computer cannot know what you mean by "reverse", since there are different ways of the "reverse of a function".
No way to 'reverse' a function. Only rewriting it is possible. Sorry.

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

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.

Categories