Delving deeper into Python functions and learning more about them, using Reuven Lerner’s Advanced Python Functions Course


  • The co_* series of attributes inside the __code__ attribute inside most functions gives a wealth of information about a function.
    • For example, looking up the argcount attribute for some function hello, with hello.__code__.co_argcount will give us the number of arguments hello takes.
    • And doing a hello.__code__.co_varnames will give us a tuple of all the local variables in a function
    • hello.__code__.co_code contains the compiled bytecode for the function.
      • Importing the disassembler import dis and running it on the bytecode, dis.dis(hello) will show us what’s in there.
    • hello.__code__.co_flags keeps a track of whether the function has * arguments or not via a binary switch. (It holds many parameters, one of which is the on/off switch for *args)
      • if said switch is set, the function checks for such arguments at runtime and turns them into a tuple to process.
      • they are set for *args via the hello.__code__co_argcount switch (0/1) and for keyword arguments with the hello.__code__.co_kwonlyargcount switch.
  • the __defaults__ attribute keeps all the functions default variable values. If I don’t supply a value to some parameter, the function will look in here, to see if a default value exists. hello.__defaults__ could hold a last name default, for example, if I want my hello function to work even if no last name was supplied, and it actually expected a full name.
    • do not use mutable defaults. an empty list or dictionary for example.
    • set the default to None first in such case and then create the list when the function runs at runtime.
  • The last thing I learnt about were nested functions.
    • I can nest them two/three/as many levels deep as I wish. Practically, most folks do two or three.
    • When an inner function takes the variables of its enclosure and does something with it and returns stuff…? those kinds of functions are called closures.

Learning / Feedback/ Experiences from doing exercises

  • The course so far is Reuven making simple functions and then breaking them down and explaining functionality in painstaking detail.
  • Reuven is an awesome teacher! I would gush about him every post, but then it would get too much 😂. So once per course is good
  • I kept looking at the disassembled code and wondering, what language it was. I still don’t know. My ‘educated’ guess is that it is a level of standard pseudo-assembly code for some phantom standardised processor. Once I had that mental model in mind though, all of it started making a lot more sense. This brought memories of Z80 assembly, I learnt in the mid 90s
  • This was fun to do! Onwards to Advanced Objects!

Read all about my Python Functions journey here