Skip to main content

Home/ Mac Attack/ Group items tagged examples

Rss Feed Group items tagged

Benjamin Bandt-Horn

25.2. doctest - Test interactive Python examples - Python v2.7.6 documentation - 0 views

  • common ways to use doctest: To check that a module’s docstrings are up-to-date by verifying that all interactive examples still work as documented. To perform regression testing by verifying that interactive examples from a test file or a test object work as expected. To write tutorial documentation for a package, liberally illustrated with input-output examples. Depending on whether the examples or the expository text are emphasized, this has the flavor of “literate testing” or “executable documentation”.
  • Running the module as a script causes the examples in the docstrings to get executed and verified
  • The file content is treated as if it were a single giant docstring; the file doesn’t need to contain a Python program! For example, perhaps example.txt contains this
  • ...8 more annotations...
  • You can instruct the Python interpreter to run the doctest module directly from the standard library and pass the file name(s) on the command line:
  • if M.__test__ exists and “is true”, it must be a dict, and each entry maps a (string) name to a function object, class object, or string
  • Which Docstrings Are Examined?
  • Any expected output must immediately follow the final '>>> ' or '... ' line containing the code, and the expected output (if any) extends to the next '>>> ' or all-whitespace line.
  • Execution Context?
  • Directives
  • Whitespace is not allowed between the + or - and the directive option name. The directive option name can be any of the option flag names explained above
  • Unittest
  •  
    Freaking Amazing.
Benjamin Bandt-Horn

gevent: A coroutine-based network library for Python - 0 views

  • gevent is a coroutine-based Python networking library that uses greenlet to provide a high-level synchronous API on top of the libev event loop. Features include: Fast event loop based on libev (epoll on Linux, kqueue on FreeBSD). Lightweight execution units based on greenlet. API that re-uses concepts from the Python standard library (for example there are Events and Queues). Cooperative sockets with SSL support » DNS queries performed through threadpool or c-ares. Monkey patching utility to get 3rd party modules to become cooperative »
  •  
    gevent is a coroutine-based Python networking library that uses greenlet to provide a high-level synchronous API on top of the libev event loop. Features include: Fast event loop based on libev (epoll on Linux, kqueue on FreeBSD). Lightweight execution units based on greenlet. API that re-uses concepts from the Python standard library (for example there are Events and Queues). Cooperative sockets with SSL support » DNS queries performed through threadpool or c-ares. Monkey patching utility to get 3rd party modules to become cooperative »
Benjamin Bandt-Horn

Great Python Tricks for avoiding unnecessary loops in your code - Udacity Forums - 0 views

  • To do element-wise operations on a list - for example, to produce a list consisting of each element of list A multiplied by 2 Method 1 [2*x for x in A] - this technique is called list comprehension Method 2 if you have defined a function double(x) which doubles x map(double, A) Method 3 define the function that doubles x on the fly, anonymously map(lambda x: 2*x, A)
  •  
    To do element-wise operations on a list - for example, to produce a list consisting of each element of list A multiplied by 2 Method 1 [2*x for x in A] - this technique is called list comprehension Method 2 if you have defined a function double(x) which doubles x map(double, A) Method 3 define the function that doubles x on the fly, anonymously map(lambda x: 2*x, A)
Benjamin Bandt-Horn

object - Build a Basic Python Iterator - Stack Overflow - 0 views

  • I just found xrange() (suprised I hadn't seen it before...) and added it to the above example. xrange() is an iterable version of range() which has the advantage of not prebuilding the list
  •  
    I just found xrange() (suprised I hadn't seen it before...) and added it to the above example. xrange() is an iterable version of range() which has the advantage of not prebuilding the list
Benjamin Bandt-Horn

Rapid GUI Programming with Python and Qt - 0 views

  • From PyQt4.6, PyQt has two APIs, API#1 (the original), and API#2 (new). API#2 is more Pythonic and eliminates QString and QVariant, and is a bit nicer to use. API#1 remains best for those using PyQt to prototype C++/Qt applications. API#1 is the default for PyQt4.x with Python 2.x, and for PyQt4.0-4.5 with Python 3.x. API#2 is the default for PyQt4.6+ with Python 3.x, and for PySide.
  • most of the changes affect uses of QDataStream, QSettings, and QTextStream, and of course any use of QString methods (since in API#2, QString is gone, so we use str).
  • To convert any particular example to PySide the steps are as follows: Replace python3 in the first line with python. Add the following statements before the first import: from __future__ import division from __future__ import print_function from future_builtins import * Replace PyQt4 with PySide throughout (e.g., in the imports) If using Python 2.6 replace {} in format strings with {0}, {1}, etc., as appropriate. Add [0] at the end of every QFileDialog.*() function call. (In PyQt these return a—possibly empty—filename; in PySide they return a filename–filter 2-tuple, but all the examples only need the filename.) Replace QT_VERSION_STR with qVersion(). Replace PYQT_VERSION_STR with PySide.__version__; you will also need to add import PySide in the imports after the future imports. Replace @pyqtSignature with @Slot. Replace def isAlive(qobj): ... with def isAlive(qobj): return True. (There is currently no PySide equivalent.) Replace chr with unichr.
Benjamin Bandt-Horn

Ternary conditional operator in Python - Stack Overflow - 0 views

  •  
    Yes, it was added in version 2.5. It's frowned upon by some pythonistas, so keep that in mind. The syntax is: a if test else b First test is evaluated, then either a or b is returned based on the Boolean value of test; if test evaluates to True a is returned, else b is returned. For example: >>> 'true' if True else 'false' 'true' >>> 'true' if False else 'false' 'false'
Benjamin Bandt-Horn

Map. - 0 views

  •  
    Combining these two special cases, we see that map(None, list1, list2) is a convenient way of turning a pair of lists into a list of pairs. For example:         >>> seq = range(8)        >>> map(None, seq, map(lambda x: x*x, seq))        [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25), (6, 36), (7, 49)]        >>>
Benjamin Bandt-Horn

python - *args and **kwargs? - Stack Overflow - 0 views

  •  
    One case where *args and **kwargs are useful is when writing wrapper functions (such as decorators) that need to be able accept arbitrary arguments to pass through to the function being wrapped. For example, a simple decorator that prints the arguments and return value of the function being wrapped: def mydecorator( f ):   @functools.wraps( f )      def wrapper( *args, **kwargs ): ...
Benjamin Bandt-Horn

!performance - Python string formatting: % vs. .format - Stack Overflow - 0 views

  • which is just ugly. .format doesn't have those issues. Also in the second example you gave, the .format example is much cleaner looking.
  •  
    .format just seems more sophisticated in many ways. You can do stuff like re-use arguments, which you can't do with %. An annoying thing about % is also how it can either take a variable or a tuple
Benjamin Bandt-Horn

Game programming - Wikipedia, the free encyclopedia - 0 views

  • The central component of any game, from a programming standpoint, is the game loop. The game loop allows the game to run smoothly regardless of a user's input or lack thereof. Most traditional software programs respond to user input and do nothing without it. For example, a word processor formats words and text as a user types. If the user doesn't type anything, the word processor does nothing. Some functions may take a long time to complete, but all are initiated by a user telling the program to do something. Games, on the other hand, must continue to operate regardless of a user's input. The game loop allows this. A highly simplified game loop, in pseudocode, might look something like this: while( user doesn't exit ) check for user input run AI move enemies resolve collisions draw graphics play sounds end while
  •  
    The central component of any game, from a programming standpoint, is the game loop. The game loop allows the game to run smoothly regardless of a user's input or lack thereof.
Benjamin Bandt-Horn

Python Package Structure with Unit Testing, Injection and Mocking - Dev Notes - 0 views

  • This describes setting up a professional Python project with a real package structure, injection and tests.
  • Since you are intended to run .py files directly, Python projects should not have source (src) or binary (bin) folders
  • For the same reason, the test folder should not be separate.  It should be a package in the main project
  • ...3 more annotations...
  • Example
  • You should specify exactly one class per file.  It makes your code easier to find and read.
  • Injection is essential for unit tests
  •  
    This describes setting up a professional Python project with a real package structure, injection and tests.
Benjamin Bandt-Horn

Accumulator Generator - 0 views

  • class foo: def __init__(self, n): self.n = n def __call__(self, i): self.n += i return self.n
  • function foo (n) { return function (i) { return n += i } }
  •  
    ...in various languages
Benjamin Bandt-Horn

Elegant ways to support equivalence ("equality") in Python classes - Stack Overflow - 0 views

  • mixin class
  • Another issue with the __dict__ comparison is what if you have an attribute that you don't want to consider in your definition of equality (say for example a unique object id, or metadata like a time created stamp).
  • isinstance sucks
  • ...4 more annotations...
  • if type(other) is type(self):
  • Check types more strictly, like this:
  • is tests for object identity. This means a is b will be True in the case when a and b both hold the reference to the same object
  • __cmp__ was removed from python 3 so avoid it
  •  
    mixin class
Benjamin Bandt-Horn

How to implement __iter__(self) for a container object (Python) - Stack Overflow - 0 views

  • usually __iter__() just return self if you have already define the next() method (generator object)
  • While you are looking at the collections module, consider inheriting from Sequence, Mapping or another abstract base class if that is more appropriate. Here is an example for a Sequence subclass:
  • if hasattr(self.data[0], "__iter__": return self.data[0].__iter__() return self.data.__iter__()
  •  
    if not self.data: raise StopIteration
1 - 14 of 14
Showing 20 items per page