I am trying to add help text to function in my python script, similar to when parentheses are opened for input() or print(). Docstrings do something similar, but isn't useful when writing the code.
See below picture for what I want. The yellow pop up text for print is something I also want to turn up for the pythagorus() function, or something similar.
I also hope to apply this to functions other than this.
Looks like you're using idle. The yellow popup you see actually is the first line of the docstring of print. Usually idle displays the method signature (except for builtins like print) and the fist line of the docstring, so if you want to show up something helpful there, then use helpful docstrings.
In python3 you can also use function annotations to hint the correct usage of your function.
Your sample function would actually make more sense if it would take two arguments and return a value. Then it could look something like this:
def pythagorus(a: int, b: int) -> int:
""" calculate a**2 + b**2
... usage example, etc ...
"""
return math.sqrt(a**2 + b**2)
Which would show up in idle like this:
Related
I am creating a module in which I'm defining multiple functions and I want to give the users some help regarding it, just like the help() function does. Still, I'm not quite sure how I do that, so can someone help me with it, for example, if I want help regarding this function, what will I have to do?
def shanky_calculate_average(*args):
my_average = sum(args) / len(args)
return my_average
I just want to know if I can get help in the same way as you can on things like help(pandas.read_excel)
What help() actually does is printing the function name with arguments and its docstring. Docstrings are comments directly after the function or class definition and are declared using either '''triple single quotes''' or """triple double quotes""".
So doing something like this:
def shanky_calculate_average(*args):
'''
Computes the average of the arguments.
Example: shanky_calculate_average(1,2,3,4)
'''
my_average = sum(args) / len(args)
return my_average
will result in help(shanky_calculate_average)
to print
shanky_calculate_average(*args)
Computes the average of the arguments.
Example: shanky_calculate_average(1,2,3,4)
As a sidenote, you can also access docstrings via the __doc__ property of the object like this: shanky_calculate_average.__doc__.
I've made a couple of python files with functions like:
def func(a,b,c):
return a+b+c
The functions are often more complicated, but the general idea of them all are the same, receive a couple of predetermined parameters, and return the desired value.
Now, I want to make a separate GUI file for easy use of all the functions. The GUI imports all the different python scripts and via text entry fields I want to be able to give the desired parameters for each function. The problem is that the functions vary greatly in what kinds of parameters they expect, so I wanted to make each function able to return a help string to the GUI with a short explanation of what the function needs to run. In the GUI file I'm using getattr to save the desired function:
methodtocall = getattr(Nuclear, func)
I can then call the function with parameters gained for textfields, like:
methodtocall(textfield1.get(),textfield2.get())
The problem, as I said above, is that for the GUI to be useful, I need a help sentence to be printed to the GUI the moment I select a function. I tried to make an adjustment in the functions themselves, example:
def func(a,b,c):
help = "give a as string, b as list, c as integer"
if no_parameters:
return help
else:
return desired_value
The problem is that the methodtocall function gives a TypeError, since I try to launch it without any parameters: methodtocall()
The solution would be something that called the desired function the moment I select it in the GUI, and retrieves the help line for the desired function and displays it in a help textfield in the GUI, does anyone have any ideas?
Place the help text in the first unassigned string in the function definition, like this:
def func(a,b,c):
"""
This function adds three numbers.
"""
return a+b+c
Now, this text is available through the variable __doc__:
print(func.__doc__)
#
# This function adds three numbers.
#
You do not even need to call the function.
Let's say, I've got a function like this:
def myFunc():
# useful function to calculate stuff
This will produce an indentation error, unless I add pass:
def myFunc():
# useful function to calculate stuff
pass
However, if I replace a comment with docstring, no pass is necessary:
def myFunc():
"""useful function to calculate stuff"""
This seems like an odd feature as neither of these are used in the program, as far as I know. So, why does it behave like this?
A comment is outright ignored by the interpreter, so omitting a block after an indent is a syntax error. However, a docstring is a real Python object--at its most basic, a literal str. A lone expression is a valid block of code:
'This is a string. It is a valid (though pretty useless) line of Python code.'
In the case of docstrings in particular, there's also some additional functionality going on, such as being used to set the __doc__ attribute.
>>> def myFunc():
... '''MyDocString'''
...
>>> print(myFunc.__doc__)
MyDocString
Note that this also works for classes:
>>> class MyClass(object):
... '''MyClassDocString'''
...
>>> print(MyClass.__doc__)
MyClassDocString
A docstring isn't just a comment. It actually has meaning to the interpreter. In the case with a docstring, you could do myFunc.__doc__ and actually get your docstring back (In the other case with a pass, the result myFunc.__doc__ would be None).
In other words, you are actually adding some code to the function body to modify it's behavior (in some circumstances), so no pass is necessary.
I'm writing a Python console application, and I would like its output to be tabbed one tab over to set it apart from the command line.
Is there a single-command way to have tabs in front of all print statements without having to type each one explicitly?
Thank you!
There isn't any setting in Python to be able to do that, the easiest way would be to create a new function like so.
def printTab(*args):
args = ("\t",)+args
print(*args)
Comment on other answers:
If you let your new function take a single argument, rather than multiple arguments (using *args, you lose a lot of the functionality in the Python 3 print function.
What you'll want to do is just create an alternate print command for this specific use. It might look something like this:
from __future__ import print_function
def print_tabbed(str_to_print):
print('\t{}'.format(str_to_print))
While there may be a way to do what you ask (see this link if that's really what you want), I think it's a bad idea and you could improve a bit on this solution.
If you define a function like this :
def printWithTab("text"):
print("\t{}").format(text)
You could use this function instead.
>>>print(test)
test
>>> printWithTab("test")
test
(assuming python 3+)
I now (or so I have read) that it is not possible in Python 2.x, and can't find it for Python 3 either, but maybe I don't know how to search for it...
It easier to explain it with a simple Python example:
for i in range(11):
one_turtle.penup()
one_turtle.forward(50)
one_turtle.down()
one_turtle.forward(8)
one_turtle.up()
one_turtle.forward(8)
one_turtle.stamp()
one_turtle.forward(-66)
one_turtle.left(360/12)
I'd like to avoid repeating "one_turtle" the same way you can do in VBA, which it would result in something similar to this:
For i = 1 To 11
With one_turtle.penup()
.forward(50)
.down()
.forward(8)
.up()
.forward(8)
.stamp()
.forward(-66)
.left(360/12)
The code resulting from the With keyword is much clearer and easy to write and read (it'll need an End With and a Next lines but I wanted to focus the discussion). One of the main reasons I have decided to learn Python is because it is said to be very neat and "zen-like" to program. Is it really not possible to do this?
In your definition of all these member-methods, simply return self.
eg. Change definition of penup() like this:
def penup(self):
# Your logic
return self
The ideal solution is I think already posted, returning self is simply the cleanest way. However if you're not able to edit the turtle object or whatever, you can create an alias:
forward = one_turtle.forward
... some code ...
forward()
Now the function forward just applies forward to one_turtle, simple example
s = "abc"
x = s.upper
print(x()) # prints "ABC"