# Observer, tester et améliorer son code python

## Anticiper

- https://www.jetbrains.com/pycharm/help/code-inspection.html

- https://wiki.python.org/moin/PythonSpeed/PerformanceTips

## Observer

- https://docs.python.org/3.8/library/profile.html

- https://pypi.org/project/pycallgraph2/

Exemple d’utilisation:

    #imports
    import cProfile
    from pycallgraph2 import PyCallGraph
    from pycallgraph2.output import GraphvizOutput

    def sonde_temps():
        """
        decorateur
        :param ma_fonction:
        :return:
        """
        def deco(function_orginale):
            def sonder(liste_entier):
                cp = cProfile.Profile()
                cp.enable()
                function_orginale(liste_entier)
                cp.disable()
                cp.print_stats()
            return sonder
        return deco

    def carre(a):
        """
        fonction appliquant un carré à la valeur passée en argument
        :param a:
        :return:
        """
        return a**2

    @sonde_temps()
    def appliquer_carre(alist):
        """
        application du carré
        :param alist:
        :return:
        """
        return list(map(carre,alist))

    if __name__ == '__main__':
        print(appliquer_carre(range(0,100000)))
        with PyCallGraph(output=GraphvizOutput(output_file='appliquer_carre.png')):
            appliquer_carre(range(0,100000))

## Tester

Via des premiers tests unitaires:

https://docs.python.org/fr/3/library/unittest.html

Exemple d’utilisation:

    import unittest

    # La fonction à tester
    def IsOdd(n):
        return n % 2 == 1

    # Un scenario de tests.
    class IsOddTests(unittest.TestCase):

        def testUn(self):
            self.assertTrue(IsOdd(1))

        def testDeux(self):

            self.assertFalse(IsOdd(2))

        def testTrois(self):
            self.assertEqual(IsOdd(2), True)

    if __name__ == '__main__':
        unittest.main()

A travers un cours complet :

https://realpython.com/python-testing