diff --git a/03-dict-set/data/text b/03-dict-set/data/text new file mode 100644 index 0000000..ecbce59 --- /dev/null +++ b/03-dict-set/data/text @@ -0,0 +1 @@ +mis ilus pikk jutt \ No newline at end of file diff --git a/03-dict-set/index.py b/03-dict-set/index.py index 3eac1fb..250b2bd 100644 --- a/03-dict-set/index.py +++ b/03-dict-set/index.py @@ -7,11 +7,12 @@ import sys import re - +import os +print(os.getcwd()) WORD_RE = re.compile('\w+') index = {} -with open(sys.argv[1], encoding='utf-8') as fp: +with open(os.path.join(os.getcwd(),"data","text"), encoding='utf-8') as fp: for line_no, line in enumerate(fp, 1): for match in WORD_RE.finditer(line): word = match.group() diff --git a/05-1class-func/bingo_my.py b/05-1class-func/bingo_my.py new file mode 100644 index 0000000..ba7a3a2 --- /dev/null +++ b/05-1class-func/bingo_my.py @@ -0,0 +1,28 @@ +import random + +class BingoCage: + + def __init__(self, items): + self._items = list(items) # <1> + random.shuffle(self._items) # <2> + + def pick(self): + #first + """some comment + and do something""" + try: + return self._items.pop() + except IndexError: + raise LookupError('pick from empty BingoCage') # <4> + + def __call__(self): # <5> + return self.pick() + +# END BINGO +bingo = BingoCage(range(3)) +print(bingo.pick()) +print(bingo()) + +callable(bingo) +random.shuffle.__doc__ +print(bingo.pick.__doc__) diff --git a/05-1class-func/bingocall.py b/05-1class-func/bingocall.py index 90c0c90..f28f5ac 100644 --- a/05-1class-func/bingocall.py +++ b/05-1class-func/bingocall.py @@ -33,3 +33,8 @@ def __call__(self): # <5> return self.pick() # END BINGO +bingo = BingoCage(range(3)) +bingo.pick() +bingo() + +callable(bingo) diff --git a/05-1class-func/tagger.py b/05-1class-func/tagger.py index f70943e..de9a6dc 100644 --- a/05-1class-func/tagger.py +++ b/05-1class-func/tagger.py @@ -42,3 +42,16 @@ def tag(name, *content, cls=None, **attrs): else: return '<%s%s />' % (name, attr_str) # END TAG_FUNC + +tag('br') # <1> + +tag('p', 'hello') # <2> + +print(tag('p', 'hello', 'world')) +tag('p', 'hello', id=33) # <3> + +print(tag('p', 'hello', 'world', cls='sidebar')) # <4> +tag(content='testing', name="img") # <5> +my_tag = {'name': 'img', 'title': 'Sunset Boulevard', + 'src': 'sunset.jpg', 'cls': 'framed'} +tag(**my_tag) # <6> diff --git a/05-1class-func/tagger_my.py b/05-1class-func/tagger_my.py new file mode 100644 index 0000000..f183384 --- /dev/null +++ b/05-1class-func/tagger_my.py @@ -0,0 +1,37 @@ +# BEGIN TAG_FUNC +def tag(name, *content, cls=None, **attrs): + """Generate one or more HTML tags""" + if cls is not None: + attrs['class'] = cls + if attrs: + attr_str = ''.join(' %s="%s"' % (attr, value) + for attr, value + in sorted(attrs.items())) + else: + attr_str = '' + if content: + return '\n'.join('<%s%s>%s' % + (name, attr_str, c, name) for c in content) + else: + return '<%s%s />' % (name, attr_str) +# END TAG_FUNC + +print(tag('br')) # <1> +print(tag('p', 'hello')) # <2> +print(tag('p', 'hello', 'world')) +print(tag('p', 'hello', id=33)) # <3> +print(tag('p', 'hello', 'world', cls='sidebar')) # <4> +print(tag(content='testing', name="img")) # <5> +my_tag = {'name': 'img', 'title': 'Sunset Boulevard', + 'src': 'sunset.jpg', 'cls': 'framed'} +print(tag(**my_tag)) + +def f(a, *,b): + return a, b + +print(f(1,b=2)) + +def f(*,a,b): + return a, b + +print(f(a=1,b=2)) \ No newline at end of file diff --git a/07-closure-deco/single_dispatch.py b/07-closure-deco/single_dispatch.py new file mode 100644 index 0000000..77608a3 --- /dev/null +++ b/07-closure-deco/single_dispatch.py @@ -0,0 +1,71 @@ +""" +Playing with python's single dispatch. +See: https://hynek.me/articles/serialization/ +See also PEP 443: https://www.python.org/dev/peps/pep-0443/ +""" +from datetime import datetime +from functools import singledispatch + + +# Let's define some custom data types (classes) +# --------------------------------------------- + +class Foo: + value = 'foo' + + def __str__(self): + return "I'm a Foo instance, named '{}'".format(self.value) + + +class Bar: + value = 'bar' + + def __str__(self): + return "I'm a Bar instance, with value = '{}'".format(self.value) + + +# And now some functions to serialize objects (i.e. convert to strings) +# --------------------------------------------------------------------- + +@singledispatch +def to_serializable(val): + """Used by default.""" + return str(val) + + +@to_serializable.register(datetime) +def ts_datetime(val): + """Used if *val* is an instance of datetime.""" + return val.isoformat() + "Z" + + +@to_serializable.register(Bar) +def ts_bar(val): + """Used if *val* is an instance of our Bar class.""" + return "BAR: {}".format(str(val)) + + +def test(): + """A function to test it all out! Create some objects then call + `to_serializable` on each of them. + """ + objects = [ + "A simple string", + datetime.now(), + Foo(), + Bar(), + ] + + for item in objects: + print(to_serializable(item)) + + # Expected output is something like: + # --------------------------------- + # A simple string + # 2016-08-23T17:02:08.665038Z + # I'm a Foo instance, named 'foo' + # BAR: I'm a Bar instance, with value = 'bar' + + +if __name__ == "__main__": + test() \ No newline at end of file