👉 Watch the video: https://www.youtube.com/watch?v=WiQqqB9MlkA 👈
Elegant Solutions for Everyday Python Problems - Pycon 2018
Are you an intermediate python developer looking to level up? Luckily, python provides us with a unique set of tools to make our code more elegant and readable by providing language features that make your code more intuitive and cut down on repetition. In this talk, I’ll share practical pythonic solutions for supercharging your code.
Specifically, I'll cover:
What magic methods are, and show you how to use them in your own code.
When and how to use partial methods.
An explanation of ContextManagers and Decorators, as well as multiple techniques for implementing them.
How to effectively use NamedTuples, and even subclass and extend them!
Lastly, I'll go over some example code that ties many of these techniques together in a cohesive way. You'll leave this talk feeling confident about using these tools and techniques in your next python project!
The tutorial will give you a brief introduction to Generators in Python. Next, you will learn the advantages of using generators in Python. Further, you will know the utility of the next() function.
After that, we will have hands-on demonstrations for Generators in Python.
The tutorial will give you a brief introduction to Generators in Python. Next, you will learn the advantages of using generators in Python. Further, you will know the utility of the next() function.
After that, we will have hands-on demonstrations for Generators in Python.
Introduction to Python Pandas for Data AnalyticsPhoenix
Pandas is an open-source, BSD-licensed Python library providing high-performance, easy-to-use data structures and data analysis tools for the Python programming language. Python with Pandas is used in a wide range of fields including academic and commercial domains including finance, economics, Statistics, analytics, medical...
What are Data structures in Python? | List, Dictionary, Tuple Explained | Edu...Edureka!
YouTube Link: https://youtu.be/m9n2f9lhtrw
** Python Certification Training: https://www.edureka.co/data-science-python-certification-course **
This Edureka video on 'Data Structures in Python' will help you understand the various data structures that Python has built into itself such as the list, dictionary, tuple and more. Further, we will also understand stacks, queues, trees and how they are implemented in Python using classes and functions. The video is divided into the following parts:
What are Data Structures?
Why are Data Structures needed?
Types of Data Structures in Python
Built-In Data Structures
Lists
Dictionary
Tuple
Sets
User-Defined Data Structure
Array
Stack
Queue
Linked List
Tree
Graph
Follow us to never miss an update in the future.
YouTube: https://www.youtube.com/user/edurekaIN
Instagram: https://www.instagram.com/edureka_learning/
Facebook: https://www.facebook.com/edurekaIN/
Twitter: https://twitter.com/edurekain
LinkedIn: https://www.linkedin.com/company/edureka
Castbox: https://castbox.fm/networks/505?country=in
Abstract: This PDSG workshop introduces the basics of Python libraries used in machine learning. Libraries covered are Numpy, Pandas and MathlibPlot.
Level: Fundamental
Requirements: One should have some knowledge of programming and some statistics.
This file contains the slides for the topic "Representing Knowledge using Rules". The slides focus mainly on difference b/w declarative and procedural knowledge, and forward & backward reasoning. In addition, the role of control knowledge in problem solving is depicted.
Association Rule Learning Part 1: Frequent Itemset GenerationKnoldus Inc.
A methodology useful for discovering interesting relationships hidden in large data sets. The uncovered relationships can be presented in the form of association rules.
Are you an intermediate Python developer looking to level up? Luckily, Python provides us with a unique set of tools to make our code more elegant and readable. I’ll share practical pythonic solutions for supercharging your code with tools like Decorators, Context Managers, and NamedTuples.
Introduction to Python Pandas for Data AnalyticsPhoenix
Pandas is an open-source, BSD-licensed Python library providing high-performance, easy-to-use data structures and data analysis tools for the Python programming language. Python with Pandas is used in a wide range of fields including academic and commercial domains including finance, economics, Statistics, analytics, medical...
What are Data structures in Python? | List, Dictionary, Tuple Explained | Edu...Edureka!
YouTube Link: https://youtu.be/m9n2f9lhtrw
** Python Certification Training: https://www.edureka.co/data-science-python-certification-course **
This Edureka video on 'Data Structures in Python' will help you understand the various data structures that Python has built into itself such as the list, dictionary, tuple and more. Further, we will also understand stacks, queues, trees and how they are implemented in Python using classes and functions. The video is divided into the following parts:
What are Data Structures?
Why are Data Structures needed?
Types of Data Structures in Python
Built-In Data Structures
Lists
Dictionary
Tuple
Sets
User-Defined Data Structure
Array
Stack
Queue
Linked List
Tree
Graph
Follow us to never miss an update in the future.
YouTube: https://www.youtube.com/user/edurekaIN
Instagram: https://www.instagram.com/edureka_learning/
Facebook: https://www.facebook.com/edurekaIN/
Twitter: https://twitter.com/edurekain
LinkedIn: https://www.linkedin.com/company/edureka
Castbox: https://castbox.fm/networks/505?country=in
Abstract: This PDSG workshop introduces the basics of Python libraries used in machine learning. Libraries covered are Numpy, Pandas and MathlibPlot.
Level: Fundamental
Requirements: One should have some knowledge of programming and some statistics.
This file contains the slides for the topic "Representing Knowledge using Rules". The slides focus mainly on difference b/w declarative and procedural knowledge, and forward & backward reasoning. In addition, the role of control knowledge in problem solving is depicted.
Association Rule Learning Part 1: Frequent Itemset GenerationKnoldus Inc.
A methodology useful for discovering interesting relationships hidden in large data sets. The uncovered relationships can be presented in the form of association rules.
Are you an intermediate Python developer looking to level up? Luckily, Python provides us with a unique set of tools to make our code more elegant and readable. I’ll share practical pythonic solutions for supercharging your code with tools like Decorators, Context Managers, and NamedTuples.
Uma equipe de apenas 14 engenheiros (junho de 2017) cuida da Infraestrutura do principal banco de dados do Facebook. Toda ação no Instagram, Messenger, WhatsApp e claro, no FB, passa direta ou indiretamente pela infra de dezenas de milhares de servidores que rodam MySQL.
A linguagem usada pela equipe e por trás de toda a automação é Python. Nessa palestra, vamos mostrar como a linguagem possibilitou que chegássemos nessa escala, passando pela evolução, desafios e futuro:
Interfaces “tipadas” com Thrift;
Empacotamento através do Buck;
Type Checking com MyPy;
Asyncio para novos serviços;
Debugging com gdb 7 e pudb;
Além disso, durante a palestra, serão discutidas algumas decisões relacionadas a DevOps que podem inspirar soluções em outros ambientes: gerenciamento de dezenas de milhares de servidores e banco de dados, backups e restores contínuos, schema migrations, entre outros.
Basics of Iterators and Generators,Uses of iterators and generators in python. advantage of iterators and generators. difference between generators and iterators.
C++ code, please help! RESPOND W COMPLETED CODE PLEASE, am using V.pdfrahulfancycorner21
C++ code, please help! RESPOND W/ COMPLETED CODE PLEASE, am using Visual Studio
Code.
Error message:
ld: Undefined symbols:
parseName(std::__1::basic_stringstream, std::__1::allocator>&), referenced from:
parseAssignments(std::__1::basic_stringstream, std::__1::allocator>&) in module-a187a7.o
SymbolTable::init(), referenced from:
_main in module-a187a7.o
parseAssignments(std::__1::basic_stringstream, std::__1::allocator>&) in module-a187a7.o
SymbolTable::insert(std::__1::basic_string, std::__1::allocator>, int), referenced from:
parseAssignments(std::__1::basic_stringstream, std::__1::allocator>&) in module-a187a7.o
SubExpression::parse(std::__1::basic_stringstream, std::__1::allocator>&), referenced from:
_main in module-a187a7.o
clang: error: linker command failed with exit code 1 (use -v to see invocation)
[Done] exited with code=1 in 1.478 seconds
divide.h
class Divide : public SubExpression
{
public:
//define the default construtor
Divide(Expression* left, Expression* right) : SubExpression(left, right)
{
}
//define the function evaluate()
int evaluate()
{
//divide the value of left and value of the right
//and return the value.
return left->evaluate() / right->evaluate();
}
};
expression.h
// Expression
class Expression
{
public:
//declare a virtual function evaluate()
virtual int evaluate() = 0;
};
literal.h
//Operand
class Literal : public Operand
{
public:
//define the construtor
Literal(int value)
{
this->value = value;
}
//define the function evaluate()
//returns the value
int evaluate()
{
return value;
}
private:
int value;
};
minus.h
//define the class Minus subclass of the SubExpression
class Minus : public SubExpression
{
public:
//define the default construtor
Minus(Expression* left, Expression* right) : SubExpression(left, right)
{
}
//define the function evaluate()
int evaluate()
{
//subtract the value of right from the value of the left
//and return the value.
return left->evaluate() - right->evaluate();
}
};
module.cpp
#include
#include
#include
#include
#include
using namespace std;
#include "expression.h"
#include "subexpression.h"
#include "symboltable.h"
#include "parse.h"
//create an object of SymbolTable
SymbolTable symbolTable;
//prototype of the function
void parseAssignments(stringstream& in);
//define main function
int main()
{
// declare the variables
Expression* expression;
char paren, comma;
string line;
// create an input file stream
ifstream fin("input.txt");
// check, if the file is not opened
//then display a error message
if (!fin.is_open())
perror("error while opening file");
//use a loop, to read the content from the file
while (getline(fin, line))
{
symbolTable.init();
if (!fin)
break;
stringstream in(line, ios_base::in);
in >> paren;
cout << line << " ";
expression = SubExpression::parse(in);
in >> comma;
//call the function
parseAssignments(in);
//Display the result
int result = expression->evaluate();
cout << "Value = " << result << endl;
}
system("pause");
return 0;
}
//definition of the function p.
Presented at EuroPython 2018
As teams and projects grow, code review becomes increasingly important to support the maintainability of complex codebases. In this talk, I’ll cover guidelines for writing consistent python code beyond pep8, how to look out for common python gotchas, and what python tools are available to automate various parts of the review process. Most importantly, I’ll cover the human aspect of code reviews - how we can be better at approaching reviews with empathy and understanding from the perspective of both a reviewer and a submitter. Following these successful code review practices will lead to happier teams and healthier code bases.
This talk is useful for python developers with any amount of experience. No prerequisite knowledge is necessary. - For those who are just starting out, it will be a great general overview. - Intermediate developers may not know about the wide variety of tooling that’s available. - Advanced developers will learn techniques for performing code reviews with empathy.
This talk will enable you to have better code reviews on your teams at work, and a better approach to code reviews in open source projects. You’ll leave with 3 main takeaways: 1. Code Reviews are most effective when conducted with empathy. If you do reviews with growth and learning in mind, they become tools for sharing knowledge instead of an opportunity to bruise egos or show off esoteric knowledge. 2. Python has powerful tooling available for code reviews such as pep8 as a style guide, pylint as a linter, coverage.py to identify test coverage, and vulture to identify dead code. 3. That python style guides beyond pep8 have clear benefits in terms of producing more consistent code that’s easier to review and easier to maintain.
How to successfully grow a code review cultureNina Zakharenko
As a team grows, code ownership is distributed. Code review becomes increasingly important to support the maintainability of complex codebases. An effective code base is on that can be worked on collaboratively by a team.
In this talk we'll discuss how to introduce a successful code review culture to your development team that will foster the idea of shared ownership. This in turn will result in a happy and healthy code base.
https://webexpo.net/prague2016/talk/how-to-successfully-grow-a-code-review-culture/
Djangocon 2014 - Django REST Framework - So Easy You Can Learn it in 25 MinutesNina Zakharenko
An introduction to the Django REST Framework, given at Djangocon US 2014.
The video for the talk is available here: https://www.youtube.com/watch?v=cqP758k1BaQ
An introduction to git and github, presented by Nina Zakharenko at Start SLC 2015 on behalf of Girl Develop It.
Prerequisites for exercises: installing git on your local machine, creating a github.com account.
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)MdTanvirMahtab2
This presentation is about the working procedure of Shahjalal Fertilizer Company Limited (SFCL). A Govt. owned Company of Bangladesh Chemical Industries Corporation under Ministry of Industries.
Cosmetic shop management system project report.pdfKamal Acharya
Buying new cosmetic products is difficult. It can even be scary for those who have sensitive skin and are prone to skin trouble. The information needed to alleviate this problem is on the back of each product, but it's thought to interpret those ingredient lists unless you have a background in chemistry.
Instead of buying and hoping for the best, we can use data science to help us predict which products may be good fits for us. It includes various function programs to do the above mentioned tasks.
Data file handling has been effectively used in the program.
The automated cosmetic shop management system should deal with the automation of general workflow and administration process of the shop. The main processes of the system focus on customer's request where the system is able to search the most appropriate products and deliver it to the customers. It should help the employees to quickly identify the list of cosmetic product that have reached the minimum quantity and also keep a track of expired date for each cosmetic product. It should help the employees to find the rack number in which the product is placed.It is also Faster and more efficient way.
Hierarchical Digital Twin of a Naval Power SystemKerry Sado
A hierarchical digital twin of a Naval DC power system has been developed and experimentally verified. Similar to other state-of-the-art digital twins, this technology creates a digital replica of the physical system executed in real-time or faster, which can modify hardware controls. However, its advantage stems from distributing computational efforts by utilizing a hierarchical structure composed of lower-level digital twin blocks and a higher-level system digital twin. Each digital twin block is associated with a physical subsystem of the hardware and communicates with a singular system digital twin, which creates a system-level response. By extracting information from each level of the hierarchy, power system controls of the hardware were reconfigured autonomously. This hierarchical digital twin development offers several advantages over other digital twins, particularly in the field of naval power systems. The hierarchical structure allows for greater computational efficiency and scalability while the ability to autonomously reconfigure hardware controls offers increased flexibility and responsiveness. The hierarchical decomposition and models utilized were well aligned with the physical twin, as indicated by the maximum deviations between the developed digital twin hierarchy and the hardware.
Final project report on grocery store management system..pdfKamal Acharya
In today’s fast-changing business environment, it’s extremely important to be able to respond to client needs in the most effective and timely manner. If your customers wish to see your business online and have instant access to your products or services.
Online Grocery Store is an e-commerce website, which retails various grocery products. This project allows viewing various products available enables registered users to purchase desired products instantly using Paytm, UPI payment processor (Instant Pay) and also can place order by using Cash on Delivery (Pay Later) option. This project provides an easy access to Administrators and Managers to view orders placed using Pay Later and Instant Pay options.
In order to develop an e-commerce website, a number of Technologies must be studied and understood. These include multi-tiered architecture, server and client-side scripting techniques, implementation technologies, programming language (such as PHP, HTML, CSS, JavaScript) and MySQL relational databases. This is a project with the objective to develop a basic website where a consumer is provided with a shopping cart website and also to know about the technologies used to develop such a website.
This document will discuss each of the underlying technologies to create and implement an e- commerce website.
Overview of the fundamental roles in Hydropower generation and the components involved in wider Electrical Engineering.
This paper presents the design and construction of hydroelectric dams from the hydrologist’s survey of the valley before construction, all aspects and involved disciplines, fluid dynamics, structural engineering, generation and mains frequency regulation to the very transmission of power through the network in the United Kingdom.
Author: Robbie Edward Sayers
Collaborators and co editors: Charlie Sims and Connor Healey.
(C) 2024 Robbie E. Sayers
Immunizing Image Classifiers Against Localized Adversary Attacksgerogepatton
This paper addresses the vulnerability of deep learning models, particularly convolutional neural networks
(CNN)s, to adversarial attacks and presents a proactive training technique designed to counter them. We
introduce a novel volumization algorithm, which transforms 2D images into 3D volumetric representations.
When combined with 3D convolution and deep curriculum learning optimization (CLO), itsignificantly improves
the immunity of models against localized universal attacks by up to 40%. We evaluate our proposed approach
using contemporary CNN architectures and the modified Canadian Institute for Advanced Research (CIFAR-10
and CIFAR-100) and ImageNet Large Scale Visual Recognition Challenge (ILSVRC12) datasets, showcasing
accuracy improvements over previous techniques. The results indicate that the combination of the volumetric
input and curriculum learning holds significant promise for mitigating adversarial attacks without necessitating
adversary training.
2. slides: h!p://bit.ly/elegant-python
This talk is for you if:
You're an intermediate python programmer
You're coming to python from another language
You want to learn about language features like: magic
methods, iterators, decorators, and context managers
@nnja
7. Magic methods start and end with a double underscore
(dunder)
By implementing a few straightforward magic methods,
you can make your objects behave like built-ins such as:
numbers
lists
dictionaries
and more...
@nnja
13. >>> soda_cost = Money('$', 5.25)
>>> pizza_cost = Money('€', 7.99)
>>> print(soda_cost + pizza_cost)
$14.33
More on Magic Methods: Dive into Python3 - Special Method
Names
14. >>> soda_cost = Money('$', 5.25)
>>> pizza_cost = Money('€', 7.99)
>>> print(soda_cost + pizza_cost)
$14.33
>>> print(pizza_cost + soda_cost)
€12.61
More on Magic Methods: Dive into Python3 - Special Method
Names
15. some magic methods map to symbols
>>> d = {'one': 1, 'two': 2}
>>> d['two']
2
>>> d.__getitem__('two')
2
@nnja
16. other magic methods map to built-in functions
class SquareShape:
def __len__(self):
""" Return the number of sides in our shape """
return 4
>>> my_square = SquareShape()
>>> len(my_square)
4
@nnja
18. Making classes iterable
In order to be iterable, a class needs to implement
__iter__()
__iter__() must return an iterator
In order to be an iterator a class needs to implement
__next__() which must raise StopIteration when
there are no more items to return
Great explanation of iterable vs. iterator vs. generator
19. Scenario..
We have a Server instance running services on
different ports.
Some services are active, some are inactive.
When we loop over our the Server instance, we only
want to loop over active services.
@nnja
21. class IterableServer:
def __init__(self):
self.current_pos = 0
def __iter__(self):
# can return self, because __next__ implemented
return self
def __next__(self):
while self.current_pos < len(self.services):
service = self.services[self.current_pos]
self.current_pos += 1
if service['active']:
return service['protocol'], service['port']
raise StopIteration
@nnja
22. class IterableServer:
def __init__(self):
self.current_pos = 0
def __iter__(self):
# can return self, because __next__ implemented
return self
def __next__(self):
while self.current_pos < len(self.services):
service = self.services[self.current_pos]
self.current_pos += 1
if service['active']:
return service['protocol'], service['port']
raise StopIteration
@nnja
23. >>> for protocol, port in IterableServer():
print('service %s on port %d' % (protocol, port))
service ssh on port 22
service http on port 80
loops over all active services ... not bad
@nnja
24. tip: use a generator
when your iterator doesn't need to
maintain a lot of state
(which is most of the time)
@nnja
25. class Server:
services = [
{'active': False, 'protocol': 'ftp', 'port': 21},
{'active': True, 'protocol': 'ssh', 'port': 22},
{'active': True, 'protocol': 'http', 'port': 21},
]
def __iter__(self):
for service in self.services:
if service['active']:
yield service['protocol'], service['port']
@nnja
26. class Server:
services = [
{'active': False, 'protocol': 'ftp', 'port': 21},
{'active': True, 'protocol': 'ssh', 'port': 22},
{'active': True, 'protocol': 'http', 'port': 21},
]
def __iter__(self):
for service in self.services:
if service['active']:
yield service['protocol'], service['port']
@nnja
27. Why does this work?
use single parenthesis ( ) to create a generator
comprehension
^ technically, a generator expression but I like this term better, and so does Ned
Batchelder
>>> my_gen = (num for num in range(1))
>>> my_gen
<generator object <genexpr> at 0x107581bf8>
@nnja
28. An iterator must implement __next__()
>>> next(my_gen) # __next__() maps to built-in next()
0
and raise StopIteration when there are no more elements
>>> next(my_gen)
... StopIteration Traceback (most recent call last)
see itertools for working with iterators
30. alias methods
class Word:
def __init__(self, word):
self.word = word
def __repr__(self):
return self.word
def __add__(self, other_word):
return Word('%s %s' % (self.word, other_word))
# Add an alias from method __add__ to the method concat
concat = __add__
@nnja
31. We can add an alias from __add__ to concat because
methods are just objects
>>> # remember, concat = __add__
>>> first_name = Word('Max')
>>> last_name = Word('Smith')
>>> first_name + last_name
Max Smith
>>> first_name.concat(last_name)
Max Smith
>>> Word.__add__ == Word.concat
True
@nnja
32. Dog class
>>> class Dog:
sound = 'Bark'
def speak(self):
print(self.sound + '!', self.sound + '!')
>>> my_dog = Dog()
>>> my_dog.speak()
Bark! Bark!
read the docs
35. Example: command line tool with dynamic commands
class Operations:
def say_hi(self, name):
print('Hello,', name)
def say_bye(self, name):
print('Goodbye,', name)
def default(self, arg):
print('This operation is not supported.')
if __name__ == '__main__':
operations = Operations()
# let's assume error handling
command, argument = input('> ').split()
getattr(operations, command, operations.default)(argument)
read the docs
36. Output
$ python demo.py
> say_hi Nina
Hello, Nina
> blah blah
This operation is not supported.
✨
additional reading - inverse of getattr() is setattr()
37. functools.partial(func, *args, **kwargs)
Return a new partial object which behaves like func
called with args & kwargs
if more arguments are passed in, they are appended
to args
if more keyword arguments are passed in, they extend
and override kwargs
read the docs on partials
38. functool.partial(func, *args, **kwargs)
# We want to be able to call this function on any int
# without having to specify the base.
>>> int('10010', base=2)
18
>>> from functools import partial
>>> basetwo = partial(int, base=2)
>>> basetwo
<functools.partial object at 0x1085a09f0>
>>> basetwo('10010')
18
read the docs on partials
39. functool.partial(func, *args, **kwargs)
# We want to be able to call this function on any int
# without having to specify the base.
>>> int('10010', base=2)
18
>>> from functools import partial
>>> basetwo = partial(int, base=2)
>>> basetwo
<functools.partial object at 0x1085a09f0>
>>> basetwo('10010')
18
read the docs on partials
40. functool.partial(func, *args, **kwargs)
# We want to be able to call this function on any int
# without having to specify the base.
>>> int('10010', base=2)
18
>>> from functools import partial
>>> basetwo = partial(int, base=2)
>>> basetwo
<functools.partial object at 0x1085a09f0>
>>> basetwo('10010')
18
read the docs on partials
42. library I
!
: github.com/mozilla/agithub
agithub is a (poorly named) REST API client with
transparent syntax which facilitates rapid prototyping
— on any REST API!
Implemented in ~400 lines.
Add support for any REST API in ~30 lines of code.
agithub knows everything it needs to about protocol
(REST, HTTP, etc), but assumes nothing about your
upstream API.
@nnja
44. then, start using the API!
>>> gh = GitHub('token')
>>> status, data = gh.user.repos.get()
>>> # ^ Maps to GET /user/repos
>>> data
... ['tweeter', 'snipey', '...']
github.com/mozilla/agithub
45. 404 if we provide a path that doesn't exist:
>>> gh = GitHub('token')
>>> status, data = gh.this.path.doesnt.exist.get()
>>> status
... 404
github.com/jpaugh/agithub
51. When should I use one?
Need to perform an action before and/or after an
operation.
Common scenarios:
Closing a resource after you're done with it (file,
network connection)
Perform cleanup before/after a function call
@nnja
52. Example Problem: Feature Flags
Turn features of your application on and off easily.
Uses of feature flags:
A/B Testing
Rolling Releases
Show Beta version to users opted-in to Beta Testing
Program
More on Feature Flags
53. class FeatureFlags:
SHOW_BETA = 'Show Beta version of Home Page'
flags = {
SHOW_BETA: True
}
@classmethod
def is_on(cls, name):
return cls.flags[name]
@classmethod
def toggle(cls, name, value):
cls.flags[name] = value
feature_flags = FeatureFlags()
@nnja
54. How do we temporarily turn features on and off when
testing flags?
Want:
with feature_flag(FeatureFlags.SHOW_BETA):
assert '/beta' == get_homepage_url()
@nnja
55. Using Magic Methods __enter__ and __exit__
class feature_flag:
""" Implementing a Context Manager using Magic Methods """
def __init__(self, name, on=True):
self.name = name
self.on = on
self.old_value = feature_flags.is_on(name)
def __enter__(self):
feature_flags.toggle(self.name, self.on)
def __exit__(self, *args):
feature_flags.toggle(self.name, self.old_value)
See: contextlib.contextmanager
56. The be!er way: using the contextmanager decorator
from contextlib import contextmanager
@contextmanager
def feature_flag(name, on=True):
old_value = feature_flags.is_on(name)
feature_flags.toggle(name, on)
yield
feature_flags.toggle(name, old_value)
See: contextlib.contextmanager
57. The be!er way: using the contextmanager decorator
from contextlib import contextmanager
@contextmanager
def feature_flag(name, on=True):
""" The easier way to create Context Managers """
old_value = feature_flags.is_on(name)
# behavior of __enter__()
feature_flags.toggle(name, on)
yield
# behavior of __exit__()
feature_flags.toggle(name, old_value)
See: contextlib.contextmanager
58. Note: yield?
from contextlib import contextmanager
@contextmanager
def feature_flag(name, on=True):
""" The easier way to create Context Managers """
old_value = feature_flags.is_on(name)
feature_flags.toggle(name, on) # behavior of __enter__()
yield
feature_flags.toggle(name, old_value) # behavior of __exit__()
See: contextlib.contextmanager
59. either implementation
def get_homepage_url():
""" Returns the path of the page to display """
if feature_flags.is_on(FeatureFlags.SHOW_BETA):
return '/beta'
else:
return '/homepage'
def test_homepage_url_with_context_manager():
with feature_flag(FeatureFlags.SHOW_BETA):
# saw the beta homepage...
assert get_homepage_url() == '/beta'
with feature_flag(FeatureFlags.SHOW_BETA, on=False):
# saw the standard homepage...
assert get_homepage_url() == '/homepage'
60. either implementation
def get_homepage_url():
""" Returns the path of the page to display """
if feature_flags.is_on(FeatureFlags.SHOW_BETA):
return '/beta'
else:
return '/homepage'
def test_homepage_url_with_context_manager():
with feature_flag(FeatureFlags.SHOW_BETA):
assert get_homepage_url() == '/beta'
print('seeing the beta homepage...')
with feature_flag(FeatureFlags.SHOW_BETA, on=False):
assert get_homepage_url() == '/homepage'
print('seeing the standard homepage...')
62. Decorators:
Wrap a function in another function.
Do something:
before the call
after the call
with provided arguments
modify the return value or arguments
@nnja
63. class User:
is_authenticated = False
def __init__(self, name):
self.name = name
Throw an exception if trying to access data only for
logged in users:
def display_profile_page(user):
""" Display profile page for logged in User """
if not user.is_authenticated:
raise Exception('User must login.')
print('Profile: %s' % user.name)
64. def enforce_authentication(func):
def wrapper(user):
if not user.is_authenticated:
raise Exception('User must login.')
return func(user)
return wrapper
the important logic:
def enforce_authentication(func):
def wrapper(user):
if not user.is_authenticated:
raise Exception('User must login.')
return func(user)
return wrapper
@nnja
65. Using enforce_authentication without a decorator:
enforce_authentication(display_profile_page)(some_user)
Or, as a decorator:
@enforce_authentication
def display_profile_page(user):
print('Profile: %s' % user.name)
Now this raises an Exception if unauthenticated:
user = User('nina')
display_profile_page(nina)
66. Problem: lost context using a decorator
>>> display_profile_page.__name__
'wrapper'
>>>> display_profile_page.__doc__
# ... empty
Solution: Use contextlib.wraps
from contextlib import wraps
def enforce_authentication(func):
@wraps(func)
def wrapper(user):
# ... rest of the code
69. By using ContextDecorator you can easily write
classes that can be used both as decorators with @
and context managers with the with statement.
ContextDecorator is used by contextmanager(),
so you get this functionality automatically .
Or, you can write a class that extends from
ContextDecorator or uses ContextDecorator as a
mixin, and implements __enter__, __exit__ and
__call__
@nnja
71. use it as a context manager
with feature_flag(FeatureFlags.SHOW_BETA):
assert get_homepage_url() == '/beta'
or use as a decorator
@feature_flag(FeatureFlags.SHOW_BETA, on=False)
def get_profile_page():
beta_flag_on = feature_flags.is_on(
FeatureFlags.SHOW_BETA)
if beta_flag_on:
return 'beta.html'
else:
return 'profile.html'
72. library I
!
: freezegun
lets your python tests ❇ travel through time! ❇
from freezegun import freeze_time
# use it as a Context Manager
def test():
with freeze_time("2012-01-14"):
assert datetime.datetime.now() == datetime.datetime(
2012, 1, 14)
assert datetime.datetime.now() != datetime.datetime(2012, 1, 14)
# or a decorator
@freeze_time("2012-01-14")
def test():
assert datetime.datetime.now() == datetime.datetime(2012, 1, 14)
read the source sometime, it's mind-bending!
73. NamedTuple
Useful when you need lightweight representations of
data.
Create tuple subclasses with named fields.
@nnja
74. Example
from collections import namedtuple
CacheInfo = namedtuple(
"CacheInfo", ["hits", "misses", "max_size", "curr_size"])
@nnja
75. Giving NamedTuples default values
RoutingRule = namedtuple(
'RoutingRule',
['prefix', 'queue_name', 'wait_time']
)
(1) By specifying defaults
RoutingRule.__new__.__defaults__ = (None, None, 20)
(2) or with _replace to customize a prototype instance
default_rule = RoutingRule(None, None, 20)
user_rule = default_rule._replace(
prefix='user', queue_name='user-queue')
76. NamedTuples can be subclassed and extended
class Person(namedtuple('Person', ['first_name', 'last_name'])):
""" Stores first and last name of a Person"""
def __str__(self):
return '%s %s' % (self.first_name, self.last_name)
>>> me = Person('nina', 'zakharenko')
>>> str(me)
'nina zakharenko'
>>> me
Person(first_name='nina', last_name='zakharenko')
77. New Tools
Magic Methods
make your objects behave like builtins (numbers,
list, dict, etc)
Method ❇Magic❇
alias methods
getattr
@nnja