Related
I am looking for a way in python to stop certain parts of the code inside a function but only when the output of the function is assigned to a variable. If the the function is run without any assignment then it should run all the inside of it.
Something like this:
def function():
print('a')
return ('a')
function()
A=function()
The first time that I call function() it should display a on the screen, while the second time nothing should print and only store value returned into A.
I have not tried anything since I am kind of new to Python, but I was imagining it would be something like the if __name__=='__main__': way of checking if a script is being used as a module or run directly.
I don't think such a behavior could be achieved in python, because within the scope of the function call, there is no indication what your will do with the returned value.
You will have to give an argument to the function that tells it to skip/stop with a default value to ease the call.
def call_and_skip(skip_instructions=False):
if not skip_instructions:
call_stuff_or_not()
call_everytime()
call_and_skip()
# will not skip inside instruction
a_variable = call_and_skip(skip_instructions=True)
# will skip inside instructions
As already mentionned in comments, what you're asking for is not technically possible - a function has (and cannot have) any knowledge of what the calling code will do with the return value.
For a simple case like your example snippet, the obvious solution is to just remove the print call from within the function and leave it out to the caller, ie:
def fun():
return 'a'
print(fun())
Now I assume your real code is a bit more complex than this so such a simple solution would not work. If that's the case, the solution is to split the original function into many distinct one and let the caller choose which part it wants to call. If you have a complex state (local variables) that need to be shared between the different parts, you can wrap the whole thing into a class, turning the sub functions into methods and storing those variables as instance attributes.
I am trying to make a python library that allows me to make custom tkinter widgets that are more aesthetically pleasing than the built-in ones. However, I have run into a problem while defining a few functions.
The problem stems from the difference between functions like append() and str(). While the append function works as follows...
somelist = ['a', 'b', 'c']
somelist.append('d')
The str() function works like this...
somenumber = 99
somenumber_text = str(some_number)
You 'call upon' the append function by (1) stating the list that you are modifying (somelist), (2) adding a period, and (3) actually naming the append funtion itself (append()). Meanwhile you 'call upon' the str function by placing a positional argument (somenumber) within its argument area. I have no idea why there is this difference, and more importantly if there is a way to specify which method to use to 'call upon' a function that I define myself?
Thanks...
In Python, function is a group of related statements that perform a specific task.
Functions help break our program into smaller and modular chunks. As our program grows larger and larger, functions make it more organized and manageable.
Furthermore, it avoids repetition and makes code reusable.
Syntax of Function
def function_name(parameters):
"""docstring"""
statement(s)
Above shown is a function definition which consists of following components.
Keyword def marks the start of function header.
A function name to uniquely identify it. Function naming follows the same rules of writing identifiers in Python.
Parameters (arguments) through which we pass values to a function. They are optional.
A colon (:) to mark the end of function header.
Optional documentation string (docstring) to describe what the function does.
One or more valid python statements that make up the function body. Statements must have same indentation level (usually 4 spaces).
An optional return statement to return a value from the function.
You really don't need to create a class, or any methods. You can make a plain-old function that's similar to bind, and just take the widget to bind as a normal parameter. For example:
def bind_multi(widget, callback, *events):
for event in events:
widget.bind(event, callback)
That means you have to call this function as bind_multi(mybutton, callback, event1, event2) instead of mybutton.bind_multi(callback, event1, event2), but there's nothing wrong with that.
I am new to Python so please don't flame me if the question is too basic :)
I have read that Python is executed from top - to - bottom.
If this is the case, why do programs go like this:
def func2():
pass
def func1():
func2()
def func():
func1()
if __name__ == '__main__':
func()
So from what I have seen, the main function goes at last and the other functions are stacked on top of it.
Am I wrong in saying this? If no, why isn't the main function or the function definitions written from top to bottom?
EDIT: I am asking why I can't do this:
if __name__ == '__main__':
func()
def func1():
func2()
Isn't this the natural order? You keep on adding stuff at the bottom, since it is executed from top to bottom.
The defs are just creating the functions. No code is executed, other than to parse the syntax and tie functions to those names.
The if is the first place code is actually executed. If you put it first, and call a function before it is defined, the result is a NameError. Therefore, you need to put it after the functions are defined.
Note that this is unlike PHP or JavaScript, where functions are 'hoisted' - any function definitions are processed and parsed before everything else. In PHP and JavaScript, it's perfectly legal to do what you are saying and define functions in the source lower down than where they are called. (One detail in JS is that functions defined like function(){} are hoisted, while functions defined like var func1=function(){}; are not. I don't know how it works with anonymous functions in PHP 5.3 yet).
See, in this, cat() will print correctly, and yip() gives you a NameError because the parser hasn't gotten to the definition of yip() at the time you call it.
def cat():
print 'meowin, yo'
cat()
yip()
def yip():
print 'barkin, yall'
meowin, yo
Traceback (most recent call last):
File "cat.py", line 5, in
yip()
NameError: name 'yip' is not defined
Python is executed from top to bottom, but executing a "def" block doesn't immediately execute the contained code. Instead it creates a function object with the given name in the current scope. Consider a Python file much like your example:
def func2():
print "func2"
def func1():
func2()
def func():
func1()
if __name__ == '__main__':
func()
What happens when this script is executed is as follows:
Firstly, a function object is created and bound to the name "func2" in the global scope. Then a function object is created and bound to the name "func1" in the global scope. Then one called "func". Then the "if" statement is executed, the condition is true and the "func()" statement is executed. At this point "func" is a function object found in the global scope, so it is invoked and its code runs. That code contains the "func1()" statement, which is resolved to a call to the "func1" function, and so on.
If you put the "if" statement at the top then when it executes there would not yet be anything defined with the name "func", so you would get an error. The important thing to recognise is that the "def" statement is itself a statement that is executed. It is not like in some other languages where definitions are a separate sort of declaration with no order of execution.
Also note that so long as the "if __name__..." bit is at the end of the file, it doesn't really matter what order the other declarations are in, since by the time any of them are called all of the "def"s will have already been executed.
Python does, in general, process commands from top to bottom. However, a function call will cause Python to execute that function, and continue downward only after that call has ended.
In your example, the Python interpreter executes the following steps:
Define func2.
Define func1.
Define func.
Process if statement if __name__ == '__main__':.
Call the func function (since the condition is true).
Call the func1 function (because that's what func does).
Call the func2 function (because that's what func1 does).
End, because after finishing the call to func2 it has also finished calling func1 and therefore has finished calling func, which was the final statement in the code.
It's also worth noting that you can have function calls written occur "before they're defined", as long as they aren't executed. Mentioning this here as it's a common new-to-python error. None of the other examples demonstrate this "it's ok, in one way" behavior. (though not really recommended)
def hi():
pie()
#hi() cannot be called here, doesn't work because hi depends on pie
def pie():
print('hi pie')
hi() # it's ok to call here!
You can even go a little further (slightly silly example, but I believe it clarifies the example)
runIt = False
def hi():
if runIt:
pie()
hi() #now ok, as the code won't call pie.
runIt = True
#hi() #wouldn't be ok as now the code will call pie.
def pie():
print('hi pie')
hi() # ok here too!
The if __name__ == "__main__" part goes at the end, because presumably whatever your main function does will need all the other definitions in the script. If there were any other function definitions below the main block, then it would not be possible for them to be used in there, since they haven't been seen by the interpreter at that point.
def statements simply define a function - they don't actually run it until the function is invoked. Hence why they generally come before whatever code uses them - they set the function up to be used in the future.
There's no hard requirement that def statements come before anything else, it's just fairly common to put the __main__ code at the bottom (among other things, it makes it clear what's in that section and what isn't, since anything below the if is part of that section). It also makes sure whatever you want to call from the section has already been def'd.
For the second part of your question (Style of coding in Python), I would take a look at PEP 8, which provides a style guide written by Guido van Rossum (the BFDL himself!) and provides the basics of writing Pythonic code.
It's true that the convention is to put the "main" function just above the "if __name__ == '__main__'" statement at the end of the file. I think that this is because we usually want functions to be near to their calling sites.
As for the called function coming above the calling function, I think that this is just a result of refactoring. At least in my case, I tend to write a function, and then take out bits of code to put into sub-functions, which I put on top so that I can see better.
This is just a primitive form of code organization. If there's a stronger cohesive unit, I'd be tempted to pull those functions into their own module.
There is two points that you need to know :
The main condition is to block the prevent code from being run when
the module is imported. In our case, the condition is true because
our file is not imported.
The code is working as follows :
Define func2
Define func1
Define func
Process if statement if __name__ == '__main__': (which in our case is True)
Call the func function
Call the func1
Call the func2 function
return the result(print the message func2)
End
I am new to Python so please don't flame me if the question is too basic :)
I have read that Python is executed from top - to - bottom.
If this is the case, why do programs go like this:
def func2():
pass
def func1():
func2()
def func():
func1()
if __name__ == '__main__':
func()
So from what I have seen, the main function goes at last and the other functions are stacked on top of it.
Am I wrong in saying this? If no, why isn't the main function or the function definitions written from top to bottom?
EDIT: I am asking why I can't do this:
if __name__ == '__main__':
func()
def func1():
func2()
Isn't this the natural order? You keep on adding stuff at the bottom, since it is executed from top to bottom.
The defs are just creating the functions. No code is executed, other than to parse the syntax and tie functions to those names.
The if is the first place code is actually executed. If you put it first, and call a function before it is defined, the result is a NameError. Therefore, you need to put it after the functions are defined.
Note that this is unlike PHP or JavaScript, where functions are 'hoisted' - any function definitions are processed and parsed before everything else. In PHP and JavaScript, it's perfectly legal to do what you are saying and define functions in the source lower down than where they are called. (One detail in JS is that functions defined like function(){} are hoisted, while functions defined like var func1=function(){}; are not. I don't know how it works with anonymous functions in PHP 5.3 yet).
See, in this, cat() will print correctly, and yip() gives you a NameError because the parser hasn't gotten to the definition of yip() at the time you call it.
def cat():
print 'meowin, yo'
cat()
yip()
def yip():
print 'barkin, yall'
meowin, yo
Traceback (most recent call last):
File "cat.py", line 5, in
yip()
NameError: name 'yip' is not defined
Python is executed from top to bottom, but executing a "def" block doesn't immediately execute the contained code. Instead it creates a function object with the given name in the current scope. Consider a Python file much like your example:
def func2():
print "func2"
def func1():
func2()
def func():
func1()
if __name__ == '__main__':
func()
What happens when this script is executed is as follows:
Firstly, a function object is created and bound to the name "func2" in the global scope. Then a function object is created and bound to the name "func1" in the global scope. Then one called "func". Then the "if" statement is executed, the condition is true and the "func()" statement is executed. At this point "func" is a function object found in the global scope, so it is invoked and its code runs. That code contains the "func1()" statement, which is resolved to a call to the "func1" function, and so on.
If you put the "if" statement at the top then when it executes there would not yet be anything defined with the name "func", so you would get an error. The important thing to recognise is that the "def" statement is itself a statement that is executed. It is not like in some other languages where definitions are a separate sort of declaration with no order of execution.
Also note that so long as the "if __name__..." bit is at the end of the file, it doesn't really matter what order the other declarations are in, since by the time any of them are called all of the "def"s will have already been executed.
Python does, in general, process commands from top to bottom. However, a function call will cause Python to execute that function, and continue downward only after that call has ended.
In your example, the Python interpreter executes the following steps:
Define func2.
Define func1.
Define func.
Process if statement if __name__ == '__main__':.
Call the func function (since the condition is true).
Call the func1 function (because that's what func does).
Call the func2 function (because that's what func1 does).
End, because after finishing the call to func2 it has also finished calling func1 and therefore has finished calling func, which was the final statement in the code.
It's also worth noting that you can have function calls written occur "before they're defined", as long as they aren't executed. Mentioning this here as it's a common new-to-python error. None of the other examples demonstrate this "it's ok, in one way" behavior. (though not really recommended)
def hi():
pie()
#hi() cannot be called here, doesn't work because hi depends on pie
def pie():
print('hi pie')
hi() # it's ok to call here!
You can even go a little further (slightly silly example, but I believe it clarifies the example)
runIt = False
def hi():
if runIt:
pie()
hi() #now ok, as the code won't call pie.
runIt = True
#hi() #wouldn't be ok as now the code will call pie.
def pie():
print('hi pie')
hi() # ok here too!
The if __name__ == "__main__" part goes at the end, because presumably whatever your main function does will need all the other definitions in the script. If there were any other function definitions below the main block, then it would not be possible for them to be used in there, since they haven't been seen by the interpreter at that point.
def statements simply define a function - they don't actually run it until the function is invoked. Hence why they generally come before whatever code uses them - they set the function up to be used in the future.
There's no hard requirement that def statements come before anything else, it's just fairly common to put the __main__ code at the bottom (among other things, it makes it clear what's in that section and what isn't, since anything below the if is part of that section). It also makes sure whatever you want to call from the section has already been def'd.
For the second part of your question (Style of coding in Python), I would take a look at PEP 8, which provides a style guide written by Guido van Rossum (the BFDL himself!) and provides the basics of writing Pythonic code.
It's true that the convention is to put the "main" function just above the "if __name__ == '__main__'" statement at the end of the file. I think that this is because we usually want functions to be near to their calling sites.
As for the called function coming above the calling function, I think that this is just a result of refactoring. At least in my case, I tend to write a function, and then take out bits of code to put into sub-functions, which I put on top so that I can see better.
This is just a primitive form of code organization. If there's a stronger cohesive unit, I'd be tempted to pull those functions into their own module.
There is two points that you need to know :
The main condition is to block the prevent code from being run when
the module is imported. In our case, the condition is true because
our file is not imported.
The code is working as follows :
Define func2
Define func1
Define func
Process if statement if __name__ == '__main__': (which in our case is True)
Call the func function
Call the func1
Call the func2 function
return the result(print the message func2)
End
I was working with generator functions and private functions of a class. I am wondering
Why when yielding (which in my one case was by accident) in __someFunc that this function just appears not to be called from within __someGenerator. Also what is the terminology I want to use when referring to these aspects of the language?
Can the python interpreter warn of such instances?
Below is an example snippet of my scenario.
class someClass():
def __init__(self):
pass
#Copy and paste mistake where yield ended up in a regular function
def __someFunc(self):
print "hello"
#yield True #if yielding in this function it isn't called
def __someGenerator (self):
for i in range(0, 10):
self.__someFunc()
yield True
yield False
def someMethod(self):
func = self.__someGenerator()
while func.next():
print "next"
sc = someClass()
sc.someMethod()
I got burned on this and spent some time trying to figure out why a function just wasn't getting called. I finally discovered I was yielding in function I didn't want to in.
A "generator" isn't so much a language feature, as a name for functions that "yield." Yielding is pretty much always legal. There's not really any way for Python to know that you didn't "mean" to yield from some function.
This PEP http://www.python.org/dev/peps/pep-0255/ talks about generators, and may help you understand the background better.
I sympathize with your experience, but compilers can't figure out what you "meant for them to do", only what you actually told them to do.
I'll try to answer the first of your questions.
A regular function, when called like this:
val = func()
executes its inside statements until it ends or a return statement is reached. Then the return value of the function is assigned to val.
If a compiler recognizes the function to actually be a generator and not a regular function (it does that by looking for yield statements inside the function -- if there's at least one, it's a generator), the scenario when calling it the same way as above has different consequences. Upon calling func(), no code inside the function is executed, and a special <generator> value is assigned to val. Then, the first time you call val.next(), the actual statements of func are being executed until a yield or return is encountered, upon which the execution of the function stops, value yielded is returned and generator waits for another call to val.next().
That's why, in your example, function __someFunc didn't print "hello" -- its statements were not executed, because you haven't called self.__someFunc().next(), but only self.__someFunc().
Unfortunately, I'm pretty sure there's no built-in warning mechanism for programming errors like yours.
Python doesn't know whether you want to create a generator object for later iteration or call a function. But python isn't your only tool for seeing what's going on with your code. If you're using an editor or IDE that allows customized syntax highlighting, you can tell it to give the yield keyword a different color, or even a bright background, which will help you find your errors more quickly, at least. In vim, for example, you might do:
:syntax keyword Yield yield
:highlight yield ctermbg=yellow guibg=yellow ctermfg=blue guifg=blue
Those are horrendous colors, by the way. I recommend picking something better. Another option, if your editor or IDE won't cooperate, is to set up a custom rule in a code checker like pylint. An example from pylint's source tarball:
from pylint.interfaces import IRawChecker
from pylint.checkers import BaseChecker
class MyRawChecker(BaseChecker):
"""check for line continuations with '\' instead of using triple
quoted string or parenthesis
"""
__implements__ = IRawChecker
name = 'custom_raw'
msgs = {'W9901': ('use \\ for line continuation',
('Used when a \\ is used for a line continuation instead'
' of using triple quoted string or parenthesis.')),
}
options = ()
def process_module(self, stream):
"""process a module
the module's content is accessible via the stream object
"""
for (lineno, line) in enumerate(stream):
if line.rstrip().endswith('\\'):
self.add_message('W9901', line=lineno)
def register(linter):
"""required method to auto register this checker"""
linter.register_checker(MyRawChecker(linter))
The pylint manual is available here: http://www.logilab.org/card/pylint_manual
And vim's syntax documentation is here: http://www.vim.org/htmldoc/syntax.html
Because the return keyword is applicable in both generator functions and regular functions, there's nothing you could possibly check (as #Christopher mentions). The return keyword in a generator indicates that a StopIteration exception should be raised.
If you try to return with a value from within a generator (which doesn't make sense, since return just means "stop iteration"), the compiler will complain at compile-time -- this may catch some copy-and-paste mistakes:
>>> def foo():
... yield 12
... return 15
...
File "<stdin>", line 3
SyntaxError: 'return' with argument inside generator
I personally just advise against copy and paste programming. :-)
From the PEP:
Note that return means "I'm done, and have nothing interesting to
return", for both generator functions and non-generator functions.
We do this.
Generators have names with "generate" or "gen" in their name. It will have a yield statement in the body. Pretty easy to check visually, since no method is much over 20 lines of code.
Other methods don't have "gen" in their name.
Also, we do not every use __ (double underscore) names under any circumstances. 32,000 lines of code. Non __ names.
The "generator vs. non-generator" method function is entirely a design question. What did the programmer "intend" to happen. The compiler can't easily validate your intent, it can only validate what you actually typed.