How to read Python function documentation [duplicate] - python

This question already has answers here:
What do square brackets, "[]", mean in function/class documentation?
(4 answers)
Closed 6 years ago.
I have a problem understanding some description of functions in Python.
I understand simply functions like os.putenv(varname, value) but I have no idea how to use this: os.getenv(varname[, value]). How to pass arguments to that function, what does those square brackets mean?

Square brackets typically mean that the value is optional. Here, varname refers to the environment variable you want to get and value is an optional value that is return if the environment variable doesn't exist.

The square brackets indicate the argument is optional. Read the description:
Return the value of the environment variable varname if it exists, or value if it doesn’t. value defaults to None.
So you can call it like this:
os.getenv('NONEXISTANTVAR')
or like this:
os.getenv('NONEXISTANTVAR', u'my default')
This first is equivalent to os.getenv('NONEXISTANTVAR', None). In the specific case of getenv, the second argument is returned if the environment variable doesn't exist.
Typically, the documentation will tell you the default value if you don't provide one, either explicitly in the description or by placing an =somevalue directly in the signature. If it doesn't indicate a specific value, then it will at least describe the difference in behavior.
unicode gives us an example of the = in the signature:
unicode(object='')
Note that in Python, the only way for an argument to be optional is for it to have a default value.

Related

I am new to python, and realized that i can assign print i.e. an inbuilt function as a variable [duplicate]

This question already has answers here:
How to restore a builtin that I overwrote by accident?
(3 answers)
Closed 2 years ago.
I am new to python, and realized that i can assign print i.e. an inbuilt function as a variable, then when i use print('hello world')this shows the exact error that i faced
I am familiar to c++ and even in that we were never allowed to use an inbuilt function as a variable name.
those were the fundamental rules for naming a variable
If python.org has issued the new version I'm sure they would have done it for a reason, bbut i want to know how do i access my print statement after assigning a value to it?
you won't be able to access your print function unless you do hacky things, which I recommend not to do them in the middle of your code.
Also it is good to know that python (as c++) has scopes for variables, and variables "die" and they are no longer accessible when scope ends. For instance:
def change_print_value():
print = 3
change_print_value()
print('Print works as expected')
It is a good practice to avoid using reserved keywords as variable names. Any IDE has the keywords highlighted, so you can easily realize when you are using a keyword where you shouldn't.
print is not part of the reserved keywords list in python. Here's a comprehensive list of reserved words.
Functions are first class objects in python, so that means they can be treated and manipulated as objects. Since print is a function (and an object), when you call print = 1, you reassign the variable print to have a value of 1, so the functionality "disappears".

Function parameter with colon [duplicate]

This question already has answers here:
What are variable annotations?
(2 answers)
Closed 3 years ago.
I just came across this function:
def splitComma(line: str):
splits = Utils.COMMA_DELIMITER.split(line)
return "{}, {}".format(splits[1], splits[2])
I am aware that you can separate parameters by , or can set a value within a parameter like a=39 but I have not seen a colon like line:str. I have checked the function definition online but could not find anything like this. What does this colon mean?
It's a function annotation; function arguments and the return value can be tagged with arbitrary Python expressions. Python itself ignores the annotation (other than saving it), but third-party tools can make use of them.
In this case, it is intended as type hint: programs like mypy can analyze your code statically (that is, without running it, but only looking at the source code itself) to ensure that only str values are passed as arguments to splitComma.
A fuller annotation to also specify the return type of the function:
def splitComma(line: str) -> str:
...
(Note that originally, function annotations weren't assumed to have any specific semantics. This is still true, but the overwhelming assumption these days is that the annotations provide type hints.)
This is a type annotation used by static analysis tools to check, well, types. It helps ensure program correctness before you run the code.

Parameter vs Argument Python [duplicate]

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.

How to print your function's documentation python [duplicate]

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.

Why does Python require the "self" parameter? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
python ‘self’ explained
Why do you need explicitly have the “self” argument into a Python method?
Why does Python require the "self" parameter for methods?
For example def method_abc(self, arg1)
And is there ever a date that the need for it will be removed?
Python gives you the option of naming it something other than self, even though the standard is to name it self. Just as it gives you the option of using tabs for indents, even though the standard is to use spaces.
In other words, it's not just "assumed" because...
To give you naming flexibility
To make it clearer that something will be passed self (or not).

Categories

Resources