Add newline for prompts so copying to REPL does not cause errors.
... for chore, days in chores.items():
... if day in days:
... print(chore)
+ ...
>>> show_chores(chores_for_ethan, Weekday.SATURDAY)
answer SO questions
... W = 2
... X = 1
... RWX = 7
+ ...
>>> Perm.RWX
<Perm.RWX: 7>
>>> ~Perm.RWX
>>> with open('args.txt', 'w', encoding=sys.getfilesystemencoding()) as fp:
... fp.write('-f\nbar')
+ ...
>>> parser = argparse.ArgumentParser(fromfile_prefix_chars='@')
>>> parser.add_argument('-f')
>>> parser.parse_args(['-f', 'foo', '@args.txt'])
>>> with bz2.open("myfile.bz2", "wb") as f:
... # Write compressed data to file
... unused = f.write(data)
+ ...
>>> with bz2.open("myfile.bz2", "rb") as f:
... # Decompress data from file
... content = f.read()
+ ...
>>> content == data # Check equality to original object after round-trip
True
>>> cnt = Counter()
>>> for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:
... cnt[word] += 1
+ ...
>>> cnt
Counter({'blue': 3, 'red': 2, 'green': 1})
>>> def constant_factory(value):
... return lambda: value
+ ...
>>> d = defaultdict(constant_factory('<missing>'))
>>> d.update(name='John', action='ran')
>>> '%(name)s %(action)s to %(object)s' % d
>>> my_birthday = date(today.year, 6, 24)
>>> if my_birthday < today:
... my_birthday = my_birthday.replace(year=today.year + 1)
+ ...
>>> my_birthday
datetime.date(2008, 6, 24)
>>> time_to_birthday = abs(my_birthday - today)
>>> def mul(x, y, fp=TWOPLACES):
... return (x * y).quantize(fp)
+ ...
>>> def div(x, y, fp=TWOPLACES):
... return (x / y).quantize(fp)
>>> def f(x):
... r'''Backslashes in a raw docstring: m\n'''
+ ...
>>> print(f.__doc__)
Backslashes in a raw docstring: m\n
>>> def f(x):
... '''Backslashes in a raw docstring: m\\n'''
+ ...
>>> print(f.__doc__)
Backslashes in a raw docstring: m\n
>>> from subprocess import Popen, PIPE
>>> with open('mymsg.txt', 'rb') as f:
... msg = message_from_binary_file(f, policy=policy.default)
+ ...
>>> p = Popen(['sendmail', msg['To'].addresses[0]], stdin=PIPE)
>>> g = BytesGenerator(p.stdin, policy=msg.policy.clone(linesep='\r\n'))
>>> g.flatten(msg)
... @classmethod
... def today(cls):
... print('today is %s' % cls(date.today().isoweekday()).name)
+ ...
>>> dir(Weekday.SATURDAY)
['__class__', '__doc__', '__eq__', '__hash__', '__module__', 'name', 'today', 'value']
... return (count + 1) * 3
... FIRST = auto()
... SECOND = auto()
+ ...
>>> PowersOfThree.SECOND.value
6
... if member.value == value:
... return member
... return None
+ ...
>>> Build.DEBUG.value
'debug'
>>> Build('deBUG')
... def __repr__(self):
... cls_name = self.__class__.__name__
... return f'{cls_name}.{self.name}'
+ ...
>>> OtherStyle.ALTERNATE, str(OtherStyle.ALTERNATE), f"{OtherStyle.ALTERNATE}"
(OtherStyle.ALTERNATE, 'OtherStyle.ALTERNATE', 'OtherStyle.ALTERNATE')
... SOMETHING_ELSE = auto()
... def __str__(self):
... return f'{self.name}'
+ ...
>>> OtherStyle.ALTERNATE, str(OtherStyle.ALTERNATE), f"{OtherStyle.ALTERNATE}"
(<OtherStyle.ALTERNATE: 1>, 'ALTERNATE', 'ALTERNATE')
... SOMETHING_ELSE = auto()
... def __format__(self, spec):
... return f'{self.name}'
+ ...
>>> OtherStyle.ALTERNATE, str(OtherStyle.ALTERNATE), f"{OtherStyle.ALTERNATE}"
(<OtherStyle.ALTERNATE: 1>, 'OtherStyle.ALTERNATE', 'ALTERNATE')
... ONE = 1
... TWO = 2
... THREE = 3
+ ...
>>> Numbers.THREE
<Numbers.THREE: 3>
>>> Numbers.ONE + Numbers.TWO
... RED = auto()
... GREEN = auto()
... BLUE = auto()
+ ...
>>> purple = Color.RED | Color.BLUE
>>> white = Color.RED | Color.GREEN | Color.BLUE
>>> Color.GREEN in purple
... RED = auto()
... GREEN = auto()
... BLUE = auto()
+ ...
>>> Color.RED & 2
<Color: 0>
>>> Color.RED | 2
... RED = auto()
... GREEN = auto()
... BLUE = auto()
+ ...
>>> StrictFlag(2**2 + 2**4)
Traceback (most recent call last):
...
... RED = auto()
... GREEN = auto()
... BLUE = auto()
+ ...
>>> ConformFlag(2**2 + 2**4)
<ConformFlag.BLUE: 4>
... RED = auto()
... GREEN = auto()
... BLUE = auto()
+ ...
>>> EjectFlag(2**2 + 2**4)
20
... RED = auto()
... GREEN = auto()
... BLUE = auto()
+ ...
>>> KeepFlag(2**2 + 2**4)
<KeepFlag.BLUE|16: 20>
>>> class Shape:
... def __dir__(self):
... return ['area', 'perimeter', 'location']
+ ...
>>> s = Shape()
>>> dir(s)
['area', 'location', 'perimeter']
>>> h = blake2b()
>>> for item in items:
... h.update(item)
+ ...
>>> h.hexdigest()
'6ff843ba685842aa82031d3f53c48b66326df7639a63d128974c5c14f31a0f33343a8c65551134ed1ae0f2b0dd2bb495dc81039e3eeb0aa1bb0388bbeac29183'
>>> def test(a, b):
... pass
+ ...
>>> sig = signature(test)
>>> new_sig = sig.replace(return_annotation="new return anno")
>>> str(new_sig)
>>> from inspect import getcallargs
>>> def f(a, b=1, *pos, **named):
... pass
+ ...
>>> getcallargs(f, 1, 2, 3) == {'a': 1, 'named': {}, 'b': 2, 'pos': (3,)}
True
>>> getcallargs(f, a=2, x=4) == {'a': 2, 'named': {'x': 4}, 'b': 1, 'pos': ()}
>>> def dashrepl(matchobj):
... if matchobj.group(0) == '-': return ' '
... else: return '-'
+ ...
>>> re.sub('-{1,2}', dashrepl, 'pro----gram-files')
'pro--gram files'
>>> re.sub(r'\sAND\s', ' & ', 'Baked Beans And Spam', flags=re.IGNORECASE)
... inner_word = list(m.group(2))
... random.shuffle(inner_word)
... return m.group(1) + "".join(inner_word) + m.group(3)
+ ...
>>> text = "Professor Abdolmalek, please report your absences promptly."
>>> re.sub(r"(\w)(\w+)(\w)", repl, text)
'Poefsrosr Aealmlobdk, pslaee reorpt your abnseces plmrptoy.'
>>> con = sqlite3.connect(":memory:")
>>> def evil_trace(stmt):
... 5/0
+ ...
>>> con.set_trace_callback(evil_trace)
>>> def debug(unraisable):
... print(f"{unraisable.exc_value!r} in callback {unraisable.object.__name__}")
>>> seed(8675309)
>>> def trial():
... return choices(('Python', 'Ruby'), (p, q), k=n).count('Python')
+ ...
>>> mean(trial() <= k for i in range(10_000))
0.8398
>>> class Counter(dict):
... def __missing__(self, key):
... return 0
+ ...
>>> c = Counter()
>>> c['red']
0
>>> n = 0
>>> for val in values:
... n += val
+ ...
>>> print(n)
504
>>> @patch.dict(foo, {'newkey': 'newvalue'})
... def test():
... assert foo == {'newkey': 'newvalue'}
+ ...
>>> test()
>>> assert foo == {}
[<Element 'a' at 0xb77ec2ac>, <Element 'a' at 0xb77ec1cc>]
>>> for i in links: # Iterates through all found links
... i.attrib["target"] = "blank"
+ ...
>>> tree.write("output.xhtml")
.. _elementtree-qname-objects:
>>> def notests(s):
... fn = os.path.basename(s)
... return (not (fn == 'test' or fn.startswith('test_')))
+ ...
>>> zf.writepy('myprog', filterfunc=notests)
The :meth:`writepy` method makes archives with file names like
>>> from inspect import getcallargs
>>> def f(a, b=1, *pos, **named):
... pass
+ ...
>>> getcallargs(f, 1, 2, 3)
{'a': 1, 'b': 2, 'pos': (3,), 'named': {}}
>>> getcallargs(f, a=2, x=4)
>>> class LowerCasedDict(dict):
... def __getitem__(self, key):
... return dict.__getitem__(self, key.lower())
+ ...
>>> lcd = LowerCasedDict(part='widgets', quantity=10)
>>> 'There are {QUANTITY} {Part} in stock'.format_map(lcd)
'There are 10 widgets in stock'
>>> class PlaceholderDict(dict):
... def __missing__(self, key):
... return '<{}>'.format(key)
+ ...
>>> 'Hello {name}, welcome to {location}'.format_map(PlaceholderDict())
'Hello <name>, welcome to <location>'
>>> from inspect import getgeneratorstate
>>> def gen():
... yield 'demo'
+ ...
>>> g = gen()
>>> getgeneratorstate(g)
'GEN_CREATED'
>>> class C:
... def meth(self):
... pass
+ ...
>>> C.meth.__name__
'meth'
>>> C.meth.__qualname__