serhii.net

In the middle of the desert you can say anything you want

05 Oct 2021

Day 1008

Python typing annotating second-order functions

def my_function(other_function: Callable) -> Callable:
  return other_function

Pycharm run all unit tests in a folder

What I’d do as

cd tests
python3 -m unittest

in Pycharm is right-clicking on a directory in Project view and “Run unittests”

OOP principles

Open/Closed principle: you should be able to open a module/class to add stuff easily, but otherwise you shouldn’t need to touch it for existing stuff.

Python dir

Wrote a line like if dir is not None .., but dir is a builtin! It returns all the names in the current scope.

Pycharm debugging

You can add Watches, values that will be shown and tracked! Nice for debugging stuff that needs values that are deep in other variables

Python unittests run at the end of the class/module

  • class-level:

    • setUpClass(cls) gets called before tests from one class get run, not once per test
    • tearDownClass(cls) gets called before tests from one class get run, not once per test
    • Both need to be class methods, a la:1
        class Test(unittest.TestCase):
            @classmethod
            def setUpClass(cls):
                cls._connection = createExpensiveConnectionObject()
      
  • module-level

    • setUpModule(), tearDownModule()
    • should be implemented as normal functions

    Aaanad if you set any class variables, you can still access them as self.xxx from within the tests!

Python or in arguments

Neat thing seen in detectron default_argument_parser:

def argparser(epilog=None):
  ...
  x = epilog or "here's some text"

Where “here’s some text” is a long string that doesn’t really belong in the function signature.

A really nice pattern, much better than my usual

if x is None:
  x = ...
Nel mezzo del deserto posso dire tutto quello che voglio.
comments powered by Disqus