May 28-30, 2018 Vikrant Patil
These notes are available online at http://notes.pipal.in/2018/vmware-advanced-may
© Pipal Academy LLP
We will be using anaconda (python 3) distribution for this training. it can be downloaded from
%%file bank0.py
balance = 0
def get_balance():
return balance
def deposite(amount):
global balance
balance += amount
def withdraw(amount):
global balance
balance -= amount
if __name__ == "__main__":
print(get_balance())
deposite(10)
print(get_balance())
deposite(5)
print(get_balance())
import bank0 as bank
%%file bank1.py
def make_account(balance=0):
return {"balance":balance}
def get_balance(account):
return account['balance']
def deposite(account, amount):
account['balance'] += amount
def witdraw(account, amount):
account['balance'] -= amount
if __name__ == "__main__":
a1 = make_account(10)
a2 = make_account()
print(get_balance(a1))
class BankAccount:
def __init__(self, balance=0, name=None):
self._balance = balance
self._name = name
self._email = "@".join([name, "vmware.com"])
def get_balance(self):
return self._balance
def get_name(self):
return self._name
def get_email(self):
return self._email
def deposite(self, amount):
self._balance += amount
def withdraw(self, amount):
self._balance -= amount
def foo():
pass
foo
BankAccount
type(BankAccount)
a1 = BankAccount(100, "Python")
a1
type(a1)
a1.get_balance()
type(range(5))
type(range)
class Foo:
x = 10
def method(self):
pass
Foo # this is class object
f = Foo() # this is instance object
a1.get_email()
ef = BankAccount.get_email
ef
mf = a1.get_email
mf
BankAccount.get_email()
a1.get_email()
a1
BankAccount.get_email(a1)
a1._email
class Foo:
x = 10
def __init__(self, y):
self.y = y
Foo.x
Foo.x
f = Foo(5)
f.x
f.y
f1 = Foo(3)
f1.x
f1.y
Foo.x = 15
f.x
f1.x
f1.x = 10
f.z = 30
f1.x = 10
f1.x
Foo.x
f.x
Foo
f
print(f)
x, y = 2, 3
x, y = y, x
l = [1,2,3]
l
print(l)
class Pair:
def __init__(self, x, y):
self.x = x
self.y = y
p = Pair(1,2)
p
class Pair:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return "Pair({0.x!r}, {0.y!r})".format(self)
def __str__(self):
return "({0.x!s}, {0.y!s})".format(self)
p1 = Pair(1,2)
p1
print(p1)
p2 = Pair(3,4)
p3 = Pair(p1, p2)
p3
print(p3)
class Pair1:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return str(self)
def __str__(self):
return "({0.x!s}, {0.y!s})".format(self)
Pair1(1,2)
str(p1)
p1.__str__()
print(p1)
repr(p1)
p1.__repr__()
p1
class Pair:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return "<Pair({0.x!r}, {0.y!r})>".format(self)
def __str__(self):
return "({0.x!s}, {0.y!s})".format(self)
def __add__(self, p):
return Pair(self.x + p.x , self.y + p.y)
def __sub__(self, p):
return Pair(self.x - p.x , self.y - p.y)
l * 2
2 * l
p1 = Pair(2,3)
p2 = (Pair(5,6))
p1 + p2
p1
p2
p2 - p1
class Pair:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return "<Pair({0.x!r}, {0.y!r})>".format(self)
def __str__(self):
return "({0.x!s}, {0.y!s})".format(self)
def __add__(self, p):
return Pair(self.x + p.x , self.y + p.y)
def __sub__(self, p):
return Pair(self.x - p.x , self.y - p.y)
def __getitem__(self, index):
if index==0:
return self.x
elif index==1:
return self.y
else:
raise IndexError("index can be only 0 or 1")
p1 = Pair(2,3)
p2 = Pair(5,8)
p1 + p2
p2 - p1
p1[0]
p1[6]
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
class ColoredPoint(Point):
color = (0,0,0)
class ColoredPoint(Point):
def __init__(self, x, y, color):
#super().__init__(x,y)
Point.__init__(self, x, y)
self.color = (0,0,0)
class Base:
def __init__(self):
print("Base")
class A(Base):
def __init__(self):
Base.__init__(self)
print("A")
class B(Base):
def __init__(self):
Base.__init__(self)
print("B")
class C(A,B):
def __init__(self):
A.__init__(self)
B.__init__(self)
print("C")
C()
class Base:
def __init__(self):
print("Base")
class A(Base):
def __init__(self):
#Base.__init__(self)
super().__init__()
print("A")
class B(Base):
def __init__(self):
#Base.__init__(self)
super().__init__()
print("B")
class C(A,B):
def __init__(self):
super().__init__()
print("C")
C()
C.__mro__
Base.__dict__
p1
p1.__dict__
problem
t = Timer()
t.start()
time.sleep(2)
t.stop()
print("Time taken for the task", t.get_time_taken())
2.001
import time
class Timer:
def start(self):
self.start_ = time.time()
def stop(self):
self.stop_ = time.time()
def time_taken(self):
return self.stop_ - self.start_
t = Timer()
t.start()
time.sleep(3)
t.stop()
print(t.time_taken())
class ContextTimer(Timer):
def __enter__(self):
print("Start of with block")
self.start()
return self
def __exit__(self, exception_type,exception_value, traceback):
self.stop()
print("End of with block")
print("Time taken:", self.time_taken())
with ContextTimer() as t:
s = 0.0
print("Inside with block")
for i in range(1000):
for j in range(10000):
s += i*j*1.0
class Bar:
pass
b = Bar()
b.x = 10
class Immutable:
def __setattr__(self, name, value):
raise Exception("No chance!")
a = Immutable()
a.x = 4
class UpperCase:
def __getattr__(self, name):
return name.upper()
u = UpperCase()
u.vmware
u.x
problem
class Foo:
def __init__(self, bar, name):
self.name = name
self.__dict__['bar'] = bar
#self.bar = bar
def __setattr__(self, name, value):
if name == "bar":
raise Exception("bar is private variable!")
elif not isinstance(value, str):
raise TypeError("Name should be a string!")
f = Foo(3, "Python")
f.bar = 5
f.name = "java"
f.name = 3
isinstance("name", str)
class OptimizedDate:
__slots__ = ["year","month","day"]
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day
d = OptimizedDate(2018,1,1)
d.year = 2013
d.x = 3
class MyDate(OptimizedDate):
def __init__(self, y, m , d, x):
super().__init__(y, m, d)
self.x = x
d = MyDate(2010,1,1,4)
d.__slots__
d.z = 3
class Foo:
def method1(self):
pass
def function():
pass
Foo.function()
Foo.method1()
class Bar:
@staticmethod
def getinstance():
return Bar()
class Foo:
def method1(self):
pass
def getinstance():
return Foo()
Foo.getinstance()
f = Foo()
f.getinstance()
Bar.getinstance()
b = Bar()
b.getinstance()
import datetime
class Mydate(datetime.datetime):
pass
d = datetime.datetime.now()
type(d)
datetime.datetime.today()
Mydate.now()
class MyInt:
def __init__(self, n):
self.n = n
@staticmethod
def parseint(strvalue):
return MyInt(int(strvalue))
MyInt.parseint("3")
class Int(MyInt):
pass
Int.parseint("4")
class MyInt:
def __init__(self, n):
self.n = n
@classmethod
def parseint(cls, strvalue):
return cls(int(strvalue))
class Int(MyInt):
pass
Int.parseint("5")
class Person:
def __init__(self, name, lastname):
self._name = name
self._lastname = lastname
@property
def email(self):
return "@".join([self._name, "vmware.com"])
@email.setter
def email(self, value):
raise Exception("Can not set email!")
@email.deleter
def email(self):
raise Exception("Can not delete email")
p = Person("anand", "c")
p.email
p.email = "abc@xyz.com"
del p.email
class Integer:
def __init__(self, name):
self.name = name
def __get__(self, instance, cls):
print("get from Integer", instance, cls)
if not instance:
return self
return instance.__dict__[self.name]
def __set__(self, instance, value):
print("set from Integer")
instance.__dict__[self.name]=value
def __delete__(self, instance):
print("delete from Integer")
raise Exception("Can not delete")
class Point:
x = Integer("x")
y = Integer("y")
def __init__(self, x , y):
self.x = x
self.y = y
p = Point(2,3)
p.x
isinstance(3, int)
3
class my_property:
def __init__(self, f):
self.f = f
def __get__(self, instance, cls):
if not instance:
return self
return self.f(instance)
class Foo:
def __init__(self, x):
self.x = x
@my_property ### name = my_property(name)
def name(self):
return "Name :" + str(self.x)
f = Foo("xyz")
f.name
from functools import wraps
def methoddebugger(cls):
def debug(f):
@wraps(f)
def wrapper(*args):
print("Debugging ..", f.__qualname__)
return f(*args)
return wrapper
for name, value in vars(cls).items():
if callable(value):
setattr(cls, name, debug(value))
return cls
@methoddebugger
class Dummy:
def mathod1(self):
pass
def method2(self):
pass
def method3(self):
pass
d = Dummy()
d.mathod1()
d.method2()
d.method3()
import threading
import time
def tick(n):
for i in range(n):
print("Tick:",i)
time.sleep(1)
t = threading.Thread(target=tick, args=(10,))
t.start()
print("*"*20)
import time
def tick(n):
for i in range(n):
print("Tick:",i)
time.sleep(1)
t = threading.Thread(target=tick, args=(10,))
t.start()
t.join()
print("*"*20) # will come here only after thread has finished task
%%file tdownload.py
import requests
import sys
import threading
def download(url):
r = requests.get(url)
r = requests.get(url)
r = requests.get(url)
filename = threading.currentThread().getName() + ".txt"
with open(filename, "w") as f:
f.write(r.text)
def spawanthread(nthreads):
args = ["http://httpbin.org/html"]*10
while args:
if len(args) < nthreads:
nthreads = len(args)
threads = []
for i in range(nthreads):
t = threading.Thread(target=download,
args=(args.pop(),),
name=str(i))
threads.append(t)
for t in threads:
t.start()
print("started thread:", t.getName())
for t in threads:
t.join()
if __name__ == "__main__":
spawanthread(int(sys.argv[1]))
!time -p python tdownload.py 1
!time -p python tdownload.py 2
!time -p python tdownload.py 4
%%file tpdownload.py
import threading
import requests
import sys
from multiprocessing.pool import ThreadPool
def download(url):
r = requests.get(url)
r = requests.get(url)
r = requests.get(url)
filename = threading.currentThread().getName() + ".txt"
print("Writing file", filename)
with open(filename, "w") as f:
f.write(r.text)
def spawanthread(nthreads):
args = ["http://httpbin.org/html"]*10
pool = ThreadPool(nthreads)
pool.map(download, args)
if __name__ == "__main__":
spawanthread(int(sys.argv[1]))
!time -p python tpdownload.py 2
!time -p python tpdownload.py 4
%%file pcpu.py
from multiprocessing.pool import Pool
import sys
def saxpy(n):
s = 0.0
for i in range(1000):
for j in range(10000):
s += i*j*1.0
return s
def spawnprocess(concurrency):
pool = Pool(concurrency)
pool.map(saxpy, [1]*10)
if __name__ == "__main__":
spawnprocess(int(sys.argv[1]))
!time -p python pcpu.py 2
!time -p python pcpu.py 1
!time -p python pcpu.py 2
!time -p python pcpu.py 4
import threading
import time
def clock(ticks, e):
for i in range(ticks):
print("Tick:",i)
time.sleep(3)
if e.isSet():
print("Boom....stoping!")
break
e = threading.Event()
t = threading.Thread(target=clock, args=(10, e))
t.start()
e.set()
%%file sockets.py
## this is python2.7 code
import SocketServer
import socket
import sys
class MyTCPHandler(SocketServer.BaseRequestHandler):
def handle(self):
data = self.request.recv(2048).strip()
print "%s wrote: " % self.client_address[0]
print data
if data=="close":
self.request.close()
self.server.shutdown()
else:
self.request.send(data.upper())
def start_server():
HOST, PORT = "127.0.0.1", 3456
server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)
server.serve_forever()
def send_client_msg():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("localhost",3456))
s.send("This is junk data KJHJKASGHD jhG ASDGH AHSGDJASGH DFJKAGH:OP{IO "*10)
received = s.recv(1024)
s.close()
print "Received: " + received
if __name__ == "__main__":
start_server()
%%file grep.py
import argparse
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("pattern",
help="Pattern to match")
parser.add_argument("file",
help="File in which pattern is searched.")
return parser.parse_args()
if __name__ == "__main__":
print(parse_args())
!python grep.py --help
!python grep.py -h "def" mymodule.py
%%file grep.py
import argparse
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("pattern",
help="Pattern to match")
parser.add_argument("file",
help="File in which pattern is searched.")
parser.add_argument("-v", "--invert",action="store_true",
help="Show lines that do not match pattern")
parser.add_argument("-n", "--number-of-matches",
type=int,
help="show only first n matches")
return parser.parse_args()
if __name__ == "__main__":
print(parse_args())
!python grep.py -h
!python grep.py -v "def " mymodule.py
!python grep.py -v -n 5 "def " mymodule.py