This question already has answers here:
How to print Docstring of python function from inside the function itself?
(8 answers)
Closed 7 years ago.
I have been searching for an answer for a lot of time now. Let's say I wrote a function in python and I made a brief documentation of what this function is doing. Is there any way to print the function's documentation from within main? Or from the function itself?
You can either use help() or print the __doc__. help() prints a more verbose description of an object while __doc__ holds only the documentation string you have defined with triple quotes """ """ in the beginning of your function.
For example, using __doc__ explicitly on the sum built-in function:
print(sum.__doc__)
Return the sum of a 'start' value (default: 0) plus an iterable of numbers
When the iterable is empty, return the start value.
This function is intended specifically for use with numeric values and may
reject non-numeric types.
Additionally, since Python first compiles an object and during execution evaluates it you can call __doc__ within the function with no problems:
def foo():
"""sample doc"""
print(foo.__doc__)
foo() # prints sample doc
and remember, besides functions, modules and classes have a __doc__ attribute holding their documentation.
Alternatively, using help() for sum:
help(sum)
Will print:
Help on built-in function sum in module builtins:
sum(iterable, start=0, /)
Return the sum of a 'start' value (default: 0) plus an iterable of numbers
When the iterable is empty, return the start value.
This function is intended specifically for use with numeric values and may
reject non-numeric types.
gives a bit more information, including the docstring.
Related
This question already has an answer here:
Why does setdefault evaluate default when key is set?
(1 answer)
Closed 6 months ago.
I don't understand the behavior of setdefault in this scenario:
def f(x):
return x+1
dct = {5: 15}
print(dct.setdefault(5, f(5)))
The key 5 is in the dictionary, but instead of returning the value 15 immediately, it wastes time computing the function at the second argument. In the end, it discards the output of f and returns 15.
Is this a bug? What is its purpose?
Python allows you to use expressions as parameters to a function. In fact, you could view all parameters as expressions. Python will evaluate all of the parameter expressions from left to right, resolving each to a single object. A function object is created, the list is expanded into the parameter set for the function, and finally the function is called.
In dct.setdefault(5, f(5)), python has no idea whether a function parameter expression will be used or not. And it can't evaluate the expression after the call is made. So, f(5) is resolved and the function is called.
If a function is expensive, then setdefault is not the tool for you. Use "not in" instead.
if 5 not in dct:
dct[5] = f(5)
In Python all arguments must be evaluated before the function is called. It would be a 'performant' behavior for this case, but could lead to consistency issues for others.
This question already has answers here:
PyCharm, what is python_stubs?
(2 answers)
Finding the source code for built-in Python functions?
(8 answers)
Closed 1 year ago.
If I go to the implementation of let's say the next() builtin function, I'm forwarded to the builtins.py module to following code:
def next(iterator, default=None): # real signature unknown; restored from __doc__
"""
next(iterator[, default])
Return the next item from the iterator. If default is given and the iterator
is exhausted, it is returned instead of raising StopIteration.
"""
pass
Now, it looks like this functions does nothing but obviously that's not the case.
I understand that this function is implemented in C under the hood, but how and when is this function(or other builtin functions) mapped to the underlying C implementation?
If you have an answer to this question, can you please also provide links that I can read in order to better unterstand this topic?
I'm not asking, where the code is, but how and when the function is mapped to that code
Thank you.
This question already has answers here:
What's the difference between an argument and a parameter?
(38 answers)
Closed last month.
So I'm still pretty new to Python and I am still confused about using a parameter vs an argument. For example, how would I write a function that accepts a string as an argument?
Generally when people say parameter/argument they mean the same thing, but the main difference between them is that the parameter is what is declared in the function, while an argument is what is passed through when calling the function.
def add(a, b):
return a+b
add(5, 4)
Here, the parameters are a and b, and the arguments being passed through are 5 and 4.
Since Python is a dynamically typed language, we do not need to declare the types of the parameters when declaring a function (unlike in other languages such as C). Thus, we can not control what exact type is passed through as an argument to the function. For example, in the above function, we could do add("hello", "hi").
This is where functions such as isinstance() are helpful because they can determine the type of an object. For example, if you do isinstance("hello", int), it will return False since "hello" is a string.
See the FAQ:
What is the difference between arguments and parameters?
Parameters are defined by the names that appear in a function definition, whereas arguments are the values actually passed to a function when calling it. Parameters define what types of arguments a function can accept. For example, given the function definition:
def func(foo, bar=None, **kwargs):
pass
foo, bar and kwargs are parameters of func. However, when calling func, for example:
func(42, bar=314, extra=somevar)
the values 42, 314, and somevar are arguments.
See also:
language-agnostic What's the difference between an argument and a parameter?
This answer is my favourite.
For defining a function that accepts a string, see TerryA's answer. I just want to mention that you can add type hints to help people using your function to tell what types it accepts, as well as what type it returns.
def greeting(name: str) -> str:
return 'Hello ' + name
In Programming lingo, arguments refers to the data you are passing to the function that is being called whereas the parameter is the name of the data and we use the parameter inside the function to refer it and do things with it.
for example:
def functionname(something):
do some stuff with {something}
functionname(abc)
in this case,
abc --> argument
something --> parameter
A parameter is the placeholder; an argument is what holds the place.
Parameters are conceptual; arguments are actual.
Parameters are the function-call signatures defined at compile-time; Arguments are the values passed at run-time.
Mnemonic: "Pee" for Placeholder Parameters, "Aeigh" for Actual Arguments.
This question already has answers here:
nargout in Python
(6 answers)
Closed 7 years ago.
In Python, do functions know how many outputs are requested? For instance, could I have a function that normally returns one output, but if two outputs are requested, it does an additional calculation and returns that too?
Or is this not the standard way to do it? In this case, it would be nice to avoid an extra function argument that says to provide a second input. But I'm interested in learning the standard way to do this.
The real and easy answer is: No.
Python functions/methods does not know about how many outputs are requested, as unpacking of a returned tuple happens after the function call.
What's quite a best practice to do though is to use underscore (_) as a placeholder for unused args that are returned from functions when they're not needed, example:
def f():
return 1, 2, 3
a, b, c = f() # if you want to use all
a, _, _ = f() # use only first element in the returned tuple, 'a'
_, b, _ = f() # use only 'b'
For example, when using underscore (_) pylint will suppress any unused argument warnings.
Python functions always return exactly 1 value.
In this case:
def myfunc():
return
that value is None. In this case:
def myfunc():
return 1, 2, 3
that value is the tuple (1, 2, 3).
So there is nothing for the function to know, really.
As for returning different outputs controlled by parameters, I'm always on the fence about that. It would depend on the actual use case. For a public API that is used by others, it is probably best to provide two separate functions with different return types, that call private code that does take the parameter.
This question already has answers here:
How to get the original variable name of variable passed to a function [duplicate]
(13 answers)
Closed 7 years ago.
I'd like to be able to access the name of a variable that is passed to a function as e.g.
def f(x):
'''Returns name of list/dict variable passed to f'''
return magic(x)
>>a = [1,2,3]
>>print( f(a) )
'a'
>>print( f(2) )
None
I suspect this is possible using Python introspection but I don't know enough to understand the inspect module. (NB I know that the need for a function like magic() is questionable, but it is what I want.)
Actually, this is not possible. In Python names and values are quite separate. Inside f, you have access to the value of x, but it is not possible to find out what other names other functions might have given to that value.
Think of names as being somewhat like pointers in C. If you have a pointer, you can find out what object it points to. But if you have the object, you cannot find out what pointers are pointing to it.