Skip to content

Instantly share code, notes, and snippets.

@blakeyoder
Last active July 24, 2017 19:36
Show Gist options
  • Save blakeyoder/267f5c1b14524109d7c0487a01557f8e to your computer and use it in GitHub Desktop.
Save blakeyoder/267f5c1b14524109d7c0487a01557f8e to your computer and use it in GitHub Desktop.
Python bits

Checking if a dictionary is empty

  • bool will return false if dict is empty
  • but wait, there's more! no need to explicitly bool cast if the object is a collection (list, dict, set, set, etc)

Truth Value Testing

What's with the with statement

  • It’s handy when you have two related operations which you’d like to execute as a pair, with a block of code in between. The classic example is opening a file, manipulating the file, then closing it

        with open('output.txt', 'w') as f:
            f.write('Hi there!')
    
  • The above with statement will automatically close the file after the nested block of code. The advantage of using a with statement is that it is guaranteed to close the file no matter how the nested block exits. If an exception occurs before the end of the block, it will close the file before the exception is caught by an outer exception handler. If the nested block were to contain a return statement, or a continue or break statement, the with statement would automatically close the file in those cases, too.

Keyword Argument Gotchas

  • Parameter defaults are only executed a single time: when the function is defined. Default argument values are evaluated only once per module load, which usually happens when a program starts up. After the module containing this code is loaded, the default argument will never be evaluated again.

  • For strings, you can specify them as defaults in the argument list

    def table_key_mapper(key_type, table_name, country='ca', stage='dev'):

  • The above is only true for default argument values that are immutable (such as strings). If you try and do this with a list, e.g. def table_key_mapper(some_arg=[1,2,3]), you're gonna have a bad time due to how Python evaluates default values at compile/load time vs. runtime, which means mutable values such as lists or dictionaries are a no-no.

Testing in Flask

  • This was first discovered when the g global object was not attaching a specific property to itself in a before_request handler.
  • The solution to the above problem can be found here in the Flask Docs
@blakeyoder
Copy link
Author

v3.0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment