Leaving values blank if not passed in str.format

You can follow the recommendation in PEP 3101 and use a subclass Formatter: import string class BlankFormatter(string.Formatter): def __init__(self, default=””): self.default=default def get_value(self, key, args, kwds): if isinstance(key, str): return kwds.get(key, self.default) else: return string.Formatter.get_value(key, args, kwds) kwargs = {“name”: “mark”, “adj”: “mad”} fmt=BlankFormatter() print fmt.format(“My name is {name} and I’m really {adj}.”, **kwargs) # … Read more

Do Dictionaries have a key length limit?

There is no such limit in place regarding dictionary keys. Since python also has arbitrary precision on numeric types, the only limit you will encounter, string or otherwise, is that of available memory. You can see another post here for a discussion on maximum string length in python 2.

how to cache asyncio coroutines

Maybe a bit late, but I’ve started a new package that may help: https://github.com/argaen/aiocache. Contributions/comments are always welcome. An example: import asyncio from collections import namedtuple from aiocache import cached from aiocache.serializers import PickleSerializer Result = namedtuple(‘Result’, “content, status”) @cached(ttl=10, serializer=PickleSerializer()) async def async_main(): print(“First ASYNC non cached call…”) await asyncio.sleep(1) return Result(“content”, 200) if … Read more

pytest assert message customization with variable introspection

you could use Python built-in capability to show custom exception message: assert response.status_code == 200, f”My custom msg: actual status code {response.status_code}” Or you can built a helper assert functions: def assert_status(response, status=200): # you can assert other status codes too assert response.status_code == status, \ f”Expected {status}. Actual status {response.status_code}. Response text {response.text}” # … Read more

How do I mock part of a python constructor just for testing?

There is no need to provide a separate constructor. Mocking patches your code to replace objects with mocks. Just use the mock.patch() decorator on your test methods; it’ll pass in references to the generated mock objects. Both producer.Producer() and consumer.Consumer() are then mocked out before you create the instance: import mock class MyTest(unittest.TestCase): @mock.patch(‘producer.Producer’, autospec=True) … Read more

How can I view a text representation of an lxml element?

From http://lxml.de/tutorial.html#serialisation >>> root = etree.XML(‘<root><a><b/></a></root>’) >>> etree.tostring(root) b'<root><a><b/></a></root>’ >>> print(etree.tostring(root, xml_declaration=True)) <?xml version=’1.0′ encoding=’ASCII’?> <root><a><b/></a></root> >>> print(etree.tostring(root, encoding=’iso-8859-1′)) <?xml version=’1.0′ encoding=’iso-8859-1′?> <root><a><b/></a></root> >>> print(etree.tostring(root, pretty_print=True)) <root> <a> <b/> </a> </root>

File not found.