I would like to provide code snippets to show-case how one could use a particular method or class in python. How can I do that?
In Java one could use <pre> ... </pre> to do so.
Doctest is the only way?
As I look at the existing docstrings for typical packages (e.g., pandas, numpy, etc), I never see anything other than doctest which is intended to test the method and not just to format text as python code. So, if doctest is the only way, what would be the proper way of formatting a snippet of code to look like interactive python sessions? I don't want to write my code in an interactive session each time and then c+p it in my docstring. It doesn't seem to be right.
DocStrings are not the only way. If you are using Sphinx to generate documentation then you should read this.
Example
Here is something I want to talk about:: <-- Special syntax to mark code beginning
def my_fn(foo, bar=True): # Code itself
"""A really useful function.
Returns None
"""
Related
For example, when i use matplotlib as plt, a possible statement is like below:
plt.plot(x,y,color='blue')
so how can i get what arguments like 'color' i can pass to the 'plot' function, and what is the proper values for that argument?
Especially when i use some modules.
thanks for any answers.
I'm a little disappointed that this post is being downvoted because I think it's a very legitimate question. In particular, I appreciate that you asked not what the answer was but instead how you could find it for yourself in the future.
Exploring Local Python Documentation
Python has a very robust built-in documentation system as well as a very active and supportive community. At any point in time, you can use the help function to examine a particular object that you want more information on - this will pull up the documentation for that object. In your example, you could do something like:
help(plt.plot)
to pull up the documentation for the matplotlib.pyplot.plot function. Outside of a running Python process, you can use the pydoc command line tool to read and explore that same documentation. Something like:
$ pydoc matplotlib.pyplot.plot
Running that in the shell will display the same documentation as the help command example.
Writing Documentation
As a good citizen of the Python ecosystem, you'll naturally want to document your own code. This is done pretty simply by adding a docstring to the top of a function, class, or module. Docstrings are denoted with a triple quotation mark """, seen in the examples below:
"""This module contains some example classes and functions"""
class MyClass(object):
"""MyClass does some things"""
pass
def my_function(a):
"""Calculates the sum"""
return(a)
There are many different documentation styles that people prefer, so what you choose is up to you. Though I would recommend the official docstring standards outlined in PEP 257.
Finding Online Resources
It's also often useful to take advantage of online documentation and resources. The official Python documentation includes all of the builtin documentation for the standard libraries as well as a tutorial for developers who are new to Python!
As it seems that you're relatively new to the ecosystem yourself, here's some more resources that you might find useful:
Learn Python the Hard Way
CodeAcademy has a Python track
StackOverflow, obviously
I recently started programming using Python. I have to write many functions and was wondering how I can incorporate a help or description text such that it appears in the object inspector of spyder when I call the function.
In MatLab, this worked by putting commented text at the beginning of the function file. Is there a similar method in Python (using Spyder)?
By default, the first string in the body of a method is used as its docstring (or documentation string). Python will use this when help() is called for that method.
def foo(bar):
"""
Takes bar and does some things to it.
"""
return bar
help(foo)
foo(bar)
Takes bar and does
some things to it
You can read more about how this works by reading PEP-258, and this question goes into some more details.
(Spyder maintainer here) There are other couple of things you need to know (besides what #burhan-khalid mentioned) regarding Spyder itself:
If you want to see your docstrings nicely formatted in the Help pane, you need to write them following the numpydoc standard, which is explained here. This is a set of conventions used by almost all python scientific packages to write their docstrings. It's not mandatory but we follow it too while converting docstrings (which come in plain text) to html.
You have to use Ctrl+I in front of an object's name to show their help in our Help pane.
In a short answer. This can be done by putting text between triple quotes.
'''
#param self
'''
You can find a brief example on this link: https://www.jetbrains.com/help/pycharm/creating-documentation-comments.html#
The other answers are more extensive.
I want to add a new functionality in python, purely for experimental purposes where I would like to extend the decorator syntax. Currently decorators can be applied on functions and classes.
I would like to also use decorators on loops (for loop for example) and also to blocks of code.
Example 1:
#foo
for i in range(20):
# do something
# and something more
Example 2:
#foo
# there's a block starting from an indent here.
# there's some code now
# do something
# and something more
Now although this is the basic idea, my requirement is to modify the body of the decorator.
For example, I want to change the loop a bit based on the decorator applied to it. I can use the AST module for this.
The problem is I do not want to completely add a new syntax and its complete implementation. I just want to parse with the new syntax, access the parse tree and the decorator's body, operate on it and insert that into the body of the program, removing the decorator thus changing the program which had a new syntax to a syntax that python has right now.
Any idea on how I would go about doing this?
You can't do that without adding new syntax. Decorators themselves don't have a "body" as such. Decorators can apply to functions or to classes and that's it. See near the top of http://docs.python.org/2/reference/grammar.html :
decorated: decorators (classdef | funcdef)
If you want something else, it can't be a decorator, it has to be your own syntax that looks like a decorator.
You could write some kind of preprocessor that parses your syntax and transforms into valid Python. One possibility is the parser module. It has facilities for parsing basic Python elements like suites (i.e., blocks). You can see a simple example in the documentation. The ast module also provides this functionality. But these modules don't provide a way to parse decorators independently of class/function defs; the decorators are essentially considered as part of the class/function defition.
Even if you manage to parse your particular construct, you will probably have to do substantial trickery to create the AST. The problem is that you can't just "access the parse tree" and "modify the AST" because the program as you've written won't have a normal Python parse tree since it can't be parsed as valid Python. So you'll have to try to stitch together your own AST by patching together your custom code with ordinary Python-parsed code.
With (very) minimal setup, how do I use emacs 23.3.1 (x86_64-apple-darwin) to show me the code for a function I am interested in?
As an example, I want to see the code for the superclass's 'db_type' in:
def db_type(self, connection):
return super(EnumField, self).db_type(connection)
I am using the django framework, however I do not believe that is relevant.
It would be nice if I could type M-. and have it bring up a list of auto-generated tags, for instance, rather than having to manually grep code myself or update tags.
try emacs for python, although that's not considered as minimal setup IMO.
Another way to ask this:
If I wrote doctests in reST, can I use it for Sphinx or other automatic documentation efforts?
Background: I don't know how to use Sphinx and have not much experience with reST either, so I am wondering if I can use reST-written doctests somewhere else useful than with Sphinx?
Why would I write doctests in restructured text?
You don't really write the tests "in restructured text". The interactive examples are the test cases, and it does not matter what the surrounding markup looks like; it could be reST, or it could be something else like Markdown or LaTeX.
reST has been adopted as the "official" markup language for Python documentation, but you are not obligated to use it.
so why is the simple usage example for doctest.testfile() from the doctest documentation then given as a reST file?
Doctest is a way to test code by checking the correctness of embedded interactive examples in documentation, so it makes sense that examples explaining the doctest module also include reST markup.
You can run doctest on text files that contain only interactive input/output examples, and no other content. Those examples could be useful as lightweight unit tests, but on their own they would be less suitable as documentation.
I am wondering if I can use reST-written doctests somewhere else useful than with Sphinx?
Having testable code examples can be useful even if you don't use Sphinx for your documentation.
If you are looking for alternative documentation tools that understand reST, take a look at docutils (which Sphinx is based on, btw) and its front-end tools, such as rst2html.py.
Another tool that might be of interest is rst2pdf.
Adding doctests to your documentation makes sense to ensure that code in your documentation is actually working as expected. So, you're testing your documentation. For general code-testing, using doctests can't be recommended at all.