{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Decorators\n", "- If you have gotten this far in your python career congrats nerd.\n", "- Here is [PEP318](https://www.python.org/dev/peps/pep-0318), it's all about decorators in python. Go a head try to read it. I have tried several times and it sucks either because it is confusing as shit or I'm stupid. IDK you decide...\n", "- Some of the code below comes from this [pretty good stackoverflow example](http://stackoverflow.com/questions/114214/class-method-differences-in-python-bound-unbound-and-static/114267#114267)\n", "- Nice explaination of [decorators](https://realpython.com/blog/python/primer-on-python-decorators/)." ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "ExecuteTime": { "end_time": "2016-12-09T13:36:49.769604", "start_time": "2016-12-09T13:36:49.751603" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Awww dang... @classmethod can'\n" ] } ], "source": [ "# Import pandas and numpy for illustration purposes.\n", "import pandas as pd\n", "import numpy as np\n", "\n", "class TestData(object):\n", " \n", " def selfDataFrame(self):\n", " return pd.DataFrame(np.random.rand(10), columns=['A'])\n", " @classmethod\n", " def classDataFrame(cls):\n", " return pd.DataFrame(np.random.rand(10), columns=['A'])\n", " @staticmethod\n", " def staticDataFrame():\n", " return pd.DataFrame(np.random.rand(10), columns=['A'])\n", "\n", "# myTest = TestData()\n", "# TestData.selfDataFrame(object)\n", "# TestData.classDataFrame()\n", "try:\n", " TestData.classDataFrame(object)\n", "except TypeError as err:\n", " print(\"Awww dang... @classmethod can'\")\n", "# TestData.staticDataFrame()" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "ExecuteTime": { "end_time": "2016-12-09T13:15:51.193618", "start_time": "2016-12-09T13:15:51.182617" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Called method_two\n" ] } ], "source": [ "class Test(object):\n", " @classmethod\n", " def method_one(cls):\n", " print(\"Called method_one\")\n", " @staticmethod\n", " def method_two():\n", " print(\"Called method_two\")\n", "\n", "# a_test = Test()\n", "# a_test.method_one()\n", "# a_test.method_two()\n", "Test.method_two()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---\n", "# Decorators with args\n", "- https://stackoverflow.com/questions/5929107/decorators-with-parameters#5929165" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Something is happening before some_function() is called.\n", "Wheee!\n", "Something is happening after some_function() is called.\n" ] } ], "source": [ "def my_decorator(some_function):\n", "\n", " def wrapper():\n", "\n", " print(\"Something is happening before some_function() is called.\")\n", "\n", " some_function()\n", "\n", " print(\"Something is happening after some_function() is called.\")\n", "\n", " return wrapper\n", "\n", "\n", "def just_some_function():\n", " print(\"Wheee!\")\n", "\n", "\n", "just_some_function = my_decorator(just_some_function)\n", "\n", "just_some_function()\n" ] }, { "cell_type": "code", "execution_count": 47, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "hello world\n", "42\n", "hi\n", "42\n" ] } ], "source": [ "def conditional_kwargs(**nkwargs):\n", " \"\"\"Returns a function that will define a keywords if they have not been not supplied.\n", " \"\"\"\n", " def decorator(some_function):\n", " def wrapper(nkwargs=nkwargs, *args, **kwargs):\n", " for k,v in nkwargs.items():\n", " if k not in kwargs:\n", " kwargs[k]=v\n", " else:\n", " pass\n", " return some_function(*args, **kwargs)\n", " return wrapper\n", " return decorator\n", "\n", " \n", "@conditional_kwargs(thing=42, greetings='hello world')\n", "def some_function(**options):\n", " print(options['greetings'])\n", " print(options['thing'])\n", " \n", "# Here I fail to supply the keyword arguments so they will be supplied by the decorator.\n", "some_function()\n", "# Here I have defined one of the keyword arguments.\n", "some_function(greetings='hi')" ] }, { "cell_type": "code", "execution_count": 48, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "http://www.google.com\n", "get\n" ] } ], "source": [ "def check_authorization(f):\n", " def wrapper(*args):\n", " print(args[0].url)\n", " return f(*args)\n", " return wrapper\n", "\n", "class Client(object):\n", " def __init__(self, url):\n", " self.url = url\n", "\n", " @check_authorization\n", " def get(self):\n", " print('get')\n", "\n", "Client('http://www.google.com').get()" ] }, { "cell_type": "code", "execution_count": 48, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "http://www.google.com\n", "get\n" ] } ], "source": [ "def check(f):\n", " def wrapper(*args):\n", " print(args[0].url)\n", " return f(*args)\n", " return wrapper\n", "\n", "class Client(object):\n", " def __init__(self, url):\n", " self.url = url\n", "\n", " @check_authorization\n", " def get(self):\n", " print('get')\n", "\n", "Client('http://www.google.com').get()" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "import functools\n", "\n", "\n", "def decorator(**dkwargs):\n", "\n", " def _decorate(function):\n", "\n", " @functools.wraps(function)\n", " def wrapped_function(*args, **kwargs):\n", " return\n", "\n", " return wrapped_function\n", "\n", " if original_function:\n", " return _decorate(original_function)\n", "\n", " return _decorate" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "26\n" ] } ], "source": [ "def parametrized(dec):\n", " def layer(*args, **kwargs):\n", " def repl(f):\n", " return dec(f, *args, **kwargs)\n", " return repl\n", " return layer\n", "\n", "@parametrized\n", "def multiply(f, n):\n", " def aux(*xs, **kws):\n", " return n * f(*xs, **kws)\n", " return aux\n", "\n", "@multiply(2)\n", "def function(a):\n", " return 10 + a\n", "\n", "print(function(3))" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "in decorator before wrapee with flag foo de fa fa\n", "in bar x y z\n", "in decorator after wrapee with flag foo de fa fa\n" ] } ], "source": [ "class MyDec(object):\n", " def __init__(self,flag):\n", " self.flag = flag\n", " def __call__(self, original_func):\n", " decorator_self = self\n", " def wrappee( *args, **kwargs):\n", " print('in decorator before wrapee with flag ',decorator_self.flag)\n", " original_func(*args,**kwargs)\n", " print('in decorator after wrapee with flag ',decorator_self.flag)\n", " return wrappee\n", "\n", "@MyDec('foo de fa fa')\n", "def bar(a,b,c):\n", " print('in bar',a,b,c)\n", "\n", "bar('x','y','z')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---\n", "## [Python decorators, the right way: the 4 audiences of programming languages](https://codewithoutrules.com/2017/08/10/python-decorators/)" ] }, { "cell_type": "code", "execution_count": 18, "metadata": { "collapsed": true }, "outputs": [], "source": [ "from threading import Lock\n", "\n", "def synchronized(function):\n", " \"\"\"\n", " Given a method, return a new method that acquires a\n", " lock, calls the given method, and then releases the\n", " lock.\n", " \"\"\"\n", " def wrapper(self, *args, **kwargs):\n", " \"\"\"A synchronized wrapper.\"\"\"\n", " with self._lock:\n", " return function(self, *args, **kwargs)\n", " return wrapper\n", "\n", "class ExampleSynchronizedClass:\n", " def __init__(self):\n", " self._lock = Lock()\n", " self._items = []\n", "\n", " # Problematic usage:\n", " def add(self, item):\n", " \"\"\"Add a new item.\"\"\"\n", " self._items.append(item)\n", " add = synchronized(add)\n", "\n", "esc = ExampleSynchronizedClass()\n", "\n", "esc.add(1)\n", "\n", "class ExampleSynchronizedClass:\n", " def __init__(self):\n", " self._lock = Lock()\n", " self._items = []\n", "\n", " # Nicer decorator usage:\n", " @synchronized\n", " def add(self, item):\n", " \"\"\"Add a new item.\"\"\"\n", " self._items.append(item)\n", "\n", "esc = ExampleSynchronizedClass()" ] }, { "cell_type": "code", "execution_count": 13, "metadata": { "collapsed": true }, "outputs": [], "source": [ "esc.add()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Decorators using wrapt." ] }, { "cell_type": "code", "execution_count": 23, "metadata": { "collapsed": true }, "outputs": [], "source": [ "import wrapt\n", "from threading import Lock\n", "\n", "@wrapt.decorator\n", "def synchronized(function, self, args, kwargs):\n", " \"\"\"\n", " Given a method, return a new method that acquires a\n", " lock, calls the given method, and then releases the\n", " lock.\n", " \"\"\"\n", " with self._lock:\n", " return function(*args, **kwargs)\n" ] }, { "cell_type": "code", "execution_count": 24, "metadata": { "collapsed": true }, "outputs": [], "source": [ "class ExampleSynchronizedClass:\n", " def __init__(self):\n", " self._lock = Lock()\n", " self._items = []\n", "\n", " # Nicer decorator usage:\n", " @synchronized\n", " def add(self, item):\n", " \"\"\"Add a new item.\"\"\"\n", " self._items.append(item)\n", "\n", "esc = ExampleSynchronizedClass()\n", "\n", "esc.add(1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---\n", "## Decorators can be used to assign properties and attributes to an instance." ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": true }, "outputs": [], "source": [ "import wrapt\n", "\n", "@wrapt.decorator\n", "def basic(function, self, args, kwargs):\n", " 'A basic decorator.'\n", " self.hello = 'hello'\n", "\n", "class Decked(object):\n", " @basic\n", " def __init__(self):\n", " pass" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'hello'" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "d = Decked()\n", "d.hello" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "----\n", "## [Python decorators with optional argument](https://codereview.stackexchange.com/a/78873/127038)" ] }, { "cell_type": "code", "execution_count": 33, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def optional_arg_decorator(fn):\n", " def wrapped_decorator(*args, **kwargs):\n", " if len(args) == 1 and len(kwargs) == 0 and callable(args[0]):\n", " return fn(args[0])\n", "\n", " else:\n", " def real_decorator(decoratee):\n", " return fn(decoratee, *args, **kwargs)\n", "\n", " return real_decorator\n", "\n", " return wrapped_decorator" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---\n", "## Meta Classes (classes are their instances) with that of Super Classes (classes are their sub-classes).\n", "\n", "- SO thread on [meta/super classes in python](https://stackoverflow.com/questions/33727217/subscriptable-objects-in-class#33728603)" ] }, { "cell_type": "code", "execution_count": 60, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Using meta __getitem__ on classes that have my type\n" ] } ], "source": [ "class MetaCls(type):\n", " def __getitem__(cls, index):\n", " print(\"Using meta __getitem__ on classes that have my type\")\n", "\n", "# metaclass is defined in header:\n", "class Base(metaclass=MetaCls):\n", " pass\n", "\n", "\n", "Base[0]" ] }, { "cell_type": "code", "execution_count": 61, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "10\n" ] } ], "source": [ "class MyMetaClass(type):\n", " def __getitem__(cls, x):\n", " return getattr(cls, x)\n", "\n", " def __new__(cls, name, parents, dct):\n", " dct[\"__getitem__\"] = cls.__getitem__\n", " return super().__new__(cls, name, parents, dct)\n", "\n", "\n", "class Dog(metaclass=MyMetaClass):\n", " x = 10\n", "\n", "d = Dog()\n", "print(d['x'])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---" ] }, { "cell_type": "code", "execution_count": 117, "metadata": {}, "outputs": [ { "ename": "AttributeError", "evalue": "type object 'Base' has no attribute '__getitem__'", "output_type": "error", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[1;31mAttributeError\u001b[0m Traceback (most recent call last)", "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[0;32m 1\u001b[0m \u001b[1;32mclass\u001b[0m \u001b[0mBase\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mobject\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 2\u001b[0m \u001b[0mx\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;36m0\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 3\u001b[1;33m \u001b[0mBase\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0m__getitem__\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[1;31mAttributeError\u001b[0m: type object 'Base' has no attribute '__getitem__'" ] } ], "source": [ "class Base(object):\n", " x = 0\n", "\n", "Base.__getitem__" ] }, { "cell_type": "code", "execution_count": 115, "metadata": { "collapsed": true }, "outputs": [], "source": [ "class Base(object):\n", " x = 0\n", " def __getitem__(self, value):\n", " return self.x.__dict__[value]" ] }, { "cell_type": "code", "execution_count": 116, "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "'type' object is not subscriptable", "output_type": "error", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)", "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mBase\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;34m'x'\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[1;31mTypeError\u001b[0m: 'type' object is not subscriptable" ] } ], "source": [ "Base['x']" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---" ] }, { "cell_type": "code", "execution_count": 130, "metadata": { "collapsed": true }, "outputs": [], "source": [ "from itertools import islice\n", "\n", "class Sliceable(object):\n", " \"\"\"Sliceable(iterable) is an object that wraps 'iterable' and\n", " generates items from 'iterable' when subscripted. For example:\n", "\n", " >>> from itertools import count, cycle\n", " >>> s = Sliceable(count())\n", " >>> list(s[3:10:2])\n", " [3, 5, 7, 9]\n", " >>> list(s[3:6])\n", " [13, 14, 15]\n", " >>> next(Sliceable(cycle(range(7)))[11])\n", " 4\n", " >>> s['string']\n", " Traceback (most recent call last):\n", " ...\n", " KeyError: 'Key must be non-negative integer or slice, not string'\n", "\n", " \"\"\"\n", " def __init__(self, iterable):\n", " self.iterable = iterable\n", "\n", " def __getitem__(self, key):\n", " if isinstance(key, int) and key >= 0:\n", " return islice(self.iterable, key, key + 1)\n", " elif isinstance(key, slice):\n", " return islice(self.iterable, key.start, key.stop, key.step)\n", " else:\n", " raise KeyError(\"Key must be non-negative integer or slice, not {}\"\n", " .format(key))" ] }, { "cell_type": "code", "execution_count": 131, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[3, 5, 7, 9]" ] }, "execution_count": 131, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from itertools import count, cycle\n", "s = Sliceable(count())\n", "list(s[3:10:2])" ] }, { "cell_type": "code", "execution_count": 132, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[10]" ] }, "execution_count": 132, "metadata": {}, "output_type": "execute_result" } ], "source": [ "list(s[0])" ] }, { "cell_type": "code", "execution_count": 136, "metadata": { "collapsed": true }, "outputs": [], "source": [ "from itertools import islice\n", "\n", "class Sliceable(object):\n", " \"\"\"Sliceable(iterable) is an object that wraps 'iterable' and\n", " generates items from 'iterable' when subscripted. For example:\n", "\n", " >>> from itertools import count, cycle\n", " >>> s = Sliceable(count())\n", " >>> list(s[3:10:2])\n", " [3, 5, 7, 9]\n", " >>> list(s[3:6])\n", " [13, 14, 15]\n", " >>> next(Sliceable(cycle(range(7)))[11])\n", " 4\n", " >>> s['string']\n", " Traceback (most recent call last):\n", " ...\n", " KeyError: 'Key must be non-negative integer or slice, not string'\n", "\n", " \"\"\"\n", " def __init__(self, iterable):\n", " self.iterable = iterable\n", "\n", " def __getitem__(self, key):\n", " if isinstance(key, int) and key >= 0:\n", " return islice(self.iterable, key, key + 1)\n", " elif isinstance(key, slice):\n", " return islice(self.iterable, key.start, key.stop, key.step)\n", " elif isinstance(key, str):\n", " if int(key) >= 0:\n", " return islice(self.iterable, int(key), int(key) + 1)\n", " \n", " else:\n", " raise KeyError(\"Key must be non-negative integer or slice, not {}\"\n", " .format(key))" ] }, { "cell_type": "code", "execution_count": 141, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[3, 5, 7, 9]" ] }, "execution_count": 141, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from itertools import count, cycle\n", "s = Sliceable(count())\n", "list(s[3:10:2])" ] }, { "cell_type": "code", "execution_count": 146, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[14]" ] }, "execution_count": 146, "metadata": {}, "output_type": "execute_result" } ], "source": [ "list(s[0])" ] }, { "cell_type": "code", "execution_count": 147, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[15]" ] }, "execution_count": 147, "metadata": {}, "output_type": "execute_result" } ], "source": [ "list(s['0'])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---" ] }, { "cell_type": "code", "execution_count": 180, "metadata": { "collapsed": true }, "outputs": [], "source": [ "class Container(object):\n", " \n", " def __init__(self,*args,**kwargs):\n", " self.value = 0\n", " \n", " def __getitem__(self, key):\n", " return self.__dict__[key]\n", " \n", " def __setitem__(self, key, value):\n", " self.__dict__[key] = value" ] }, { "cell_type": "code", "execution_count": 181, "metadata": { "collapsed": true }, "outputs": [], "source": [ "c = Container()" ] }, { "cell_type": "code", "execution_count": 182, "metadata": { "collapsed": true }, "outputs": [], "source": [ "c['value'] = 1" ] }, { "cell_type": "code", "execution_count": 184, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 184, "metadata": {}, "output_type": "execute_result" } ], "source": [ "c.value" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---" ] }, { "cell_type": "code", "execution_count": 202, "metadata": { "collapsed": true }, "outputs": [], "source": [ "import wrapt\n", "\n", "@wrapt.decorator\n", "def basic(function, self, args, kwargs):\n", " 'A basic decorator.'\n", " self.hello = 'hello'" ] }, { "cell_type": "code", "execution_count": 214, "metadata": { "collapsed": true }, "outputs": [], "source": [ "import wrapt\n", "\n", "@wrapt.decorator\n", "def dict_like(function, self, *args, **kwargs):\n", " \n", " def __getitem__(self, key):\n", " return self.__dict__[key]\n", " \n", " def __setitem__(self, key, value):\n", " self.__dict__[key] = value\n", " \n", " setattr(self, '__getitem__', __getitem__)" ] }, { "cell_type": "code", "execution_count": 215, "metadata": { "collapsed": true }, "outputs": [], "source": [ "class Decked(object):\n", " @dict_like\n", " def __init__(self):\n", " self.hello = 0\n", " pass" ] }, { "cell_type": "code", "execution_count": 216, "metadata": { "collapsed": true }, "outputs": [], "source": [ "d = Decked()" ] }, { "cell_type": "code", "execution_count": 217, "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "'Decked' object is not subscriptable", "output_type": "error", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)", "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0md\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;34m'hello'\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[1;31mTypeError\u001b[0m: 'Decked' object is not subscriptable" ] } ], "source": [ "d['hello']" ] }, { "cell_type": "code", "execution_count": 218, "metadata": { "collapsed": true }, "outputs": [], "source": [ "class F(object):\n", " def __init__(self, fn):\n", " self.__dict__['fn'] = fn\n", "\n", " def __call__(self, *args, **kwargs):\n", " return self.fn(*args, **kwargs)\n", "\n", " def __getitem__(self, name):\n", " return name\n", "\n", " def __getattr__(self, name):\n", " return name" ] }, { "cell_type": "code", "execution_count": 221, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def foo():\n", " print('hello')\n", "\n", "foo = F(foo)" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "---" ] }, { "cell_type": "code", "execution_count": 19, "metadata": { "collapsed": true }, "outputs": [], "source": [ "import time\n", "from functools import wraps\n", "\n", "\n", "def function_timer(some_function):\n", " \"\"\"Return the time a function takes to execute.\"\"\"\n", " @wraps(some_function)\n", " def wrapper():\n", " t1 = time.time()\n", " some_function()\n", " t2 = time.time()\n", " return '{}: {}'.format(some_function.__name__, str((t2 - t1)))\n", " return wrapper" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Sum of all the numbers: 4999950000\n", "my_function: 0.015599727630615234\n" ] } ], "source": [ "@function_timer\n", "def my_function():\n", " num_list = []\n", " for num in (range(0, 100000)):\n", " num_list.append(num)\n", " print(\"\\nSum of all the numbers: \" + str((sum(num_list))))\n", "\n", "\n", "print(my_function())" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'my_function'" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "my_function.__name__" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "---" ] }, { "cell_type": "code", "execution_count": 40, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 40, "metadata": {}, "output_type": "execute_result" } ], "source": [ "def class_dec(self):\n", " setattr(self, 'hello', 1)\n", " return self\n", "\n", "@class_dec\n", "class DecoratedClass(object): \n", " pass\n", "\n", "dc = DecoratedClass()\n", "\n", "dc.hello" ] }, { "cell_type": "code", "execution_count": 39, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "" ] }, "execution_count": 39, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from tkinter import Frame, ttk\n", "from functools import partial\n", "\n", "def button_entry(self, attrname):\n", " setattr(self, '_'.join([attrname, 'button']), ttk.Button())\n", " return self\n", "\n", "button_entry_dec = partial(button_entry, attrname='thing')\n", "\n", "@button_entry_dec\n", "class DecoratedTk(object):\n", " \n", " def __init__(self):\n", " pass\n", "\n", "dtk = DecoratedTk()\n", "dtk.thing_button" ] }, { "cell_type": "code", "execution_count": 39, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "" ] }, "execution_count": 39, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from tkinter import Frame, ttk\n", "from functools import partial\n", "\n", "def button_entry(self):\n", " setattr(self, '_'.join([attrname, 'button']), ttk.Button())\n", " partial(button_entry, attrname='thing')\n", " return self\n", "\n", "button_entry_dec = partial(button_entry, attrname='thing')\n", "\n", "@button_entry_dec\n", "class DecoratedTk(object):\n", " \n", " def __init__(self):\n", " pass\n", "\n", "dtk = DecoratedTk()\n", "dtk.thing_button" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---" ] }, { "cell_type": "code", "execution_count": 53, "metadata": { "collapsed": true }, "outputs": [], "source": [ "\n", "def button_dec(prop):\n", " def wrapper(self, *args, **kwargs):\n", " \n", " return wrapper\n", "\n", "\n", "class ExampleClass:\n", " def __init__(self):\n", " pass\n", "\n", " @button_dec\n", " def add(self):\n", " pass\n", "\n", "esc = ExampleClass()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---" ] }, { "cell_type": "code", "execution_count": 18, "metadata": { "scrolled": false }, "outputs": [ { "data": { "text/plain": [ "['_Misc__winfo_getint',\n", " '_Misc__winfo_parseitem',\n", " '__class__',\n", " '__delattr__',\n", " '__dict__',\n", " '__dir__',\n", " '__doc__',\n", " '__eq__',\n", " '__format__',\n", " '__ge__',\n", " '__getattr__',\n", " '__getattribute__',\n", " '__getitem__',\n", " '__gt__',\n", " '__hash__',\n", " '__init__',\n", " '__init_subclass__',\n", " '__le__',\n", " '__lt__',\n", " '__module__',\n", " '__ne__',\n", " '__new__',\n", " '__reduce__',\n", " '__reduce_ex__',\n", " '__repr__',\n", " '__setattr__',\n", " '__setitem__',\n", " '__sizeof__',\n", " '__str__',\n", " '__subclasshook__',\n", " '__weakref__',\n", " '_bind',\n", " '_configure',\n", " '_displayof',\n", " '_getboolean',\n", " '_getconfigure',\n", " '_getconfigure1',\n", " '_getdoubles',\n", " '_getints',\n", " '_grid_configure',\n", " '_gridconvvalue',\n", " '_last_child_ids',\n", " '_loadtk',\n", " '_nametowidget',\n", " '_noarg_',\n", " '_options',\n", " '_register',\n", " '_report_exception',\n", " '_root',\n", " '_subst_format',\n", " '_subst_format_str',\n", " '_substitute',\n", " '_tclCommands',\n", " '_w',\n", " '_windowingsystem',\n", " 'after',\n", " 'after_cancel',\n", " 'after_idle',\n", " 'anchor',\n", " 'aspect',\n", " 'attributes',\n", " 'bbox',\n", " 'bell',\n", " 'bind',\n", " 'bind_all',\n", " 'bind_class',\n", " 'bindtags',\n", " 'cget',\n", " 'client',\n", " 'clipboard_append',\n", " 'clipboard_clear',\n", " 'clipboard_get',\n", " 'colormapwindows',\n", " 'columnconfigure',\n", " 'command',\n", " 'config',\n", " 'configure',\n", " 'deiconify',\n", " 'deletecommand',\n", " 'destroy',\n", " 'event_add',\n", " 'event_delete',\n", " 'event_generate',\n", " 'event_info',\n", " 'focus',\n", " 'focus_displayof',\n", " 'focus_force',\n", " 'focus_get',\n", " 'focus_lastfor',\n", " 'focus_set',\n", " 'focusmodel',\n", " 'forget',\n", " 'frame',\n", " 'geometry',\n", " 'getboolean',\n", " 'getdouble',\n", " 'getint',\n", " 'getvar',\n", " 'grab_current',\n", " 'grab_release',\n", " 'grab_set',\n", " 'grab_set_global',\n", " 'grab_status',\n", " 'grid',\n", " 'grid_anchor',\n", " 'grid_bbox',\n", " 'grid_columnconfigure',\n", " 'grid_location',\n", " 'grid_propagate',\n", " 'grid_rowconfigure',\n", " 'grid_size',\n", " 'grid_slaves',\n", " 'group',\n", " 'iconbitmap',\n", " 'iconify',\n", " 'iconmask',\n", " 'iconname',\n", " 'iconphoto',\n", " 'iconposition',\n", " 'iconwindow',\n", " 'image_names',\n", " 'image_types',\n", " 'keys',\n", " 'lift',\n", " 'loadtk',\n", " 'lower',\n", " 'mainloop',\n", " 'manage',\n", " 'maxsize',\n", " 'minsize',\n", " 'nametowidget',\n", " 'option_add',\n", " 'option_clear',\n", " 'option_get',\n", " 'option_readfile',\n", " 'overrideredirect',\n", " 'pack_propagate',\n", " 'pack_slaves',\n", " 'place_slaves',\n", " 'positionfrom',\n", " 'propagate',\n", " 'protocol',\n", " 'quit',\n", " 'readprofile',\n", " 'register',\n", " 'report_callback_exception',\n", " 'resizable',\n", " 'rowconfigure',\n", " 'selection_clear',\n", " 'selection_get',\n", " 'selection_handle',\n", " 'selection_own',\n", " 'selection_own_get',\n", " 'send',\n", " 'setvar',\n", " 'size',\n", " 'sizefrom',\n", " 'slaves',\n", " 'state',\n", " 'title',\n", " 'tk_bisque',\n", " 'tk_focusFollowsMouse',\n", " 'tk_focusNext',\n", " 'tk_focusPrev',\n", " 'tk_setPalette',\n", " 'tk_strictMotif',\n", " 'tkraise',\n", " 'transient',\n", " 'unbind',\n", " 'unbind_all',\n", " 'unbind_class',\n", " 'update',\n", " 'update_idletasks',\n", " 'wait_variable',\n", " 'wait_visibility',\n", " 'wait_window',\n", " 'waitvar',\n", " 'winfo_atom',\n", " 'winfo_atomname',\n", " 'winfo_cells',\n", " 'winfo_children',\n", " 'winfo_class',\n", " 'winfo_colormapfull',\n", " 'winfo_containing',\n", " 'winfo_depth',\n", " 'winfo_exists',\n", " 'winfo_fpixels',\n", " 'winfo_geometry',\n", " 'winfo_height',\n", " 'winfo_id',\n", " 'winfo_interps',\n", " 'winfo_ismapped',\n", " 'winfo_manager',\n", " 'winfo_name',\n", " 'winfo_parent',\n", " 'winfo_pathname',\n", " 'winfo_pixels',\n", " 'winfo_pointerx',\n", " 'winfo_pointerxy',\n", " 'winfo_pointery',\n", " 'winfo_reqheight',\n", " 'winfo_reqwidth',\n", " 'winfo_rgb',\n", " 'winfo_rootx',\n", " 'winfo_rooty',\n", " 'winfo_screen',\n", " 'winfo_screencells',\n", " 'winfo_screendepth',\n", " 'winfo_screenheight',\n", " 'winfo_screenmmheight',\n", " 'winfo_screenmmwidth',\n", " 'winfo_screenvisual',\n", " 'winfo_screenwidth',\n", " 'winfo_server',\n", " 'winfo_toplevel',\n", " 'winfo_viewable',\n", " 'winfo_visual',\n", " 'winfo_visualid',\n", " 'winfo_visualsavailable',\n", " 'winfo_vrootheight',\n", " 'winfo_vrootwidth',\n", " 'winfo_vrootx',\n", " 'winfo_vrooty',\n", " 'winfo_width',\n", " 'winfo_x',\n", " 'winfo_y',\n", " 'withdraw',\n", " 'wm_aspect',\n", " 'wm_attributes',\n", " 'wm_client',\n", " 'wm_colormapwindows',\n", " 'wm_command',\n", " 'wm_deiconify',\n", " 'wm_focusmodel',\n", " 'wm_forget',\n", " 'wm_frame',\n", " 'wm_geometry',\n", " 'wm_grid',\n", " 'wm_group',\n", " 'wm_iconbitmap',\n", " 'wm_iconify',\n", " 'wm_iconmask',\n", " 'wm_iconname',\n", " 'wm_iconphoto',\n", " 'wm_iconposition',\n", " 'wm_iconwindow',\n", " 'wm_manage',\n", " 'wm_maxsize',\n", " 'wm_minsize',\n", " 'wm_overrideredirect',\n", " 'wm_positionfrom',\n", " 'wm_protocol',\n", " 'wm_resizable',\n", " 'wm_sizefrom',\n", " 'wm_state',\n", " 'wm_title',\n", " 'wm_transient',\n", " 'wm_withdraw']" ] }, "execution_count": 18, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from tkinter import Tk\n", "dir(Tk)" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "---" ] }, { "cell_type": "code", "execution_count": 16, "metadata": { "collapsed": true }, "outputs": [], "source": [ "%gui\n", "\n", "from sneakers.ttk import window, button, showInfo\n", "\n", "def ex0():\n", " # Tk windows \n", " with window() as w:\n", " # Change window properties like normal tkinter.\n", " w.attributes(\"-topmost\", True)\n", " # Give a custom size and or postion.\n", " w.geometry('200x300+100+100')\n", " # Create buttons using decorators.\n", " @button(\"Create a popup box\")\n", " # Attach a function to the button by defining it below the decorator.\n", " def makePopupBox():\n", " showInfo(message = \"Hello World!\")\n", "\n", "ex0()" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": true }, "outputs": [], "source": [ "%gui\n", "\n", "from sneakers.ttk import window, button, showInfo\n", "\n", "def ex0():\n", " with window() as w:\n", " # Change window properties like normal tkinter.\n", " w.attributes(\"-topmost\", True)\n", " # Give a custom size and or postion.\n", " w.geometry('200x300+100+100')\n", " # Create buttons using decorators.\n", " @button(\"Create a popup box\")\n", " # Attach a function to the button by defining it below the decorator.\n", " def makePopupBox():\n", " showInfo(message = \"Hello World!\")\n", "\n", "ex0()" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": true }, "outputs": [], "source": [ "from tkinter import filedialog\n", "\n", "n = filedialog.askopenfilename()" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "('C:/Users/t440p/Documents/JupyterNotebooks/DMPI/Muoio_Lab/S3vDS3vDKOSkm_10plex/pd22_result_data/Ashley Williams_S3vDS3vDKOSkm_10plex_Acetyl.Phospho.Input.v2_PeptideGroups.txt',)" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from tkinter import Tk, filedialog\n", "\n", "def select_files():\n", " root = Tk()\n", " root.attributes('-topmost', True)\n", " root.withdraw()\n", " return filedialog.askopenfilenames(parent=root)\n", "\n", "select_files()" ] }, { "cell_type": "code", "execution_count": 14, "metadata": { "collapsed": true, "scrolled": false }, "outputs": [], "source": [ "from tkinter import filedialog\n", "# dir(filedialog)" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "ename": "ModuleNotFoundError", "evalue": "No module named 'tkinter.ttk.tkinter'; 'tkinter.ttk' is not a package", "output_type": "error", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[1;31mModuleNotFoundError\u001b[0m Traceback (most recent call last)", "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[0;32m 3\u001b[0m \u001b[1;31m# dir(ttk)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 4\u001b[0m \u001b[1;31m# dir(ttk.tkinter)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 5\u001b[1;33m \u001b[1;32mfrom\u001b[0m \u001b[0mtkinter\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mttk\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mtkinter\u001b[0m \u001b[1;32mimport\u001b[0m \u001b[0mfiledialog\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 6\u001b[0m \u001b[0mdir\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mfiledialog\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n", "\u001b[1;31mModuleNotFoundError\u001b[0m: No module named 'tkinter.ttk.tkinter'; 'tkinter.ttk' is not a package" ] } ], "source": [ "from tkinter import ttk\n", "\n", "# dir(ttk)\n", "# dir(ttk.tkinter)\n", "# from tkinter.ttk.tkinter import filedialog\n", "# dir(filedialog)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "%gui\n", "from sneakers.ttk import window, button, filedialog\n", "\n", "def ex0():\n", " with window() as w:\n", " # Change window properties like normal tkinter.\n", " # w.attributes(\"-topmost\", True)\n", " w.withdraw()\n", " \n", " file_path = filedialog.askopenfilename()\n", " print(file_path)\n", " \n", " return file_path\n", "ex0()" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "hi\n" ] } ], "source": [ "print('hi')" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "collapsed": true, "scrolled": false }, "outputs": [], "source": [ "# from tkinter import simpledialog\n", "# dir(simpledialog)" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# dir(simpledialog.filedialog)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [] } ], "metadata": { "anaconda-cloud": {}, "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.3" }, "varInspector": { "cols": { "lenName": 16, "lenType": 16, "lenVar": 40 }, "kernels_config": { "python": { "delete_cmd_postfix": "", "delete_cmd_prefix": "del ", "library": "var_list.py", "varRefreshCmd": "print(var_dic_list())" }, "r": { "delete_cmd_postfix": ") ", "delete_cmd_prefix": "rm(", "library": "var_list.r", "varRefreshCmd": "cat(var_dic_list()) " } }, "types_to_exclude": [ "module", "function", "builtin_function_or_method", "instance", "_Feature" ], "window_display": false } }, "nbformat": 4, "nbformat_minor": 1 }