This will fail if kwargs['chain'] does not exist. There needs to be some quick sanity checking here. There probably should have been some already for kwargs['table'], except that table is required, and you have made chain optional.