Skip to content

Commit 684823a

Browse files
committed
end of 7.3
1 parent b17a510 commit 684823a

7 files changed

Lines changed: 94 additions & 35 deletions

File tree

Work/exercise7.3.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
2+
3+
def after(seconds, func, *args):
4+
import time
5+
time.sleep(seconds)
6+
# print(len(args))
7+
func(args)
8+
9+
10+
def greeting(a):
11+
print(a)
12+
for i in a:
13+
print(f'Hello Guido, {i}')
14+
15+
after(2, greeting,*range(5), 'you old asshole!') # unpacking the range
16+

Work/report.py

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -19,17 +19,22 @@ def read_prices(filename):
1919
prices = parse_csv(f, types=[str,float], has_headers=False)
2020
return dict(prices)
2121

22-
def read_portfolio(filename):
22+
def read_portfolio(filename, **opts):
2323
"""
2424
Reads a stock portfolio from a CSV file with handling for missing files.
2525
Returns a list of Stock objects.
2626
"""
2727

2828
with open(filename) as f:
29-
portdicts = parse_csv(f, types=[str, int, float])
29+
portdicts = parse_csv(f,
30+
select=['name','shares','price'],
31+
types=[str, int, float],
32+
**opts)
3033

31-
portfolio = [ Stock(d['name'], d['shares'], d['price']) for d in portdicts]
32-
return Portfolio(portfolio)
34+
# stock_data = [ Stock(d['name'], d['shares'], d['price']) for d in portdicts]
35+
stock_data = [ Stock(**d) for d in portdicts]
36+
37+
return Portfolio(stock_data)
3338

3439
def make_report(portfolio, prices):
3540
'''
@@ -91,15 +96,15 @@ def main(argv):
9196
pf_file = argv[1]
9297
price_file = argv[2]
9398
fmt = argv[3] if len(argv) > 3 else 'txt' # Default to 'txt' if format is not provided
94-
99+
95100
portfolio_report(pf_file, price_file, fmt)
96101

97102

98103
if __name__ == '__main__':
99104
import sys
100105
# print('this prints when file is executed as main, not imported')
101106
if len(sys.argv) not in [3, 4]:
102-
raise SystemExit(f'Usage: {sys.argv[0]} ' 'portfile pricefile <format>')
107+
raise SystemExit(f'Usage: {sys.argv[0]} ' 'portfile pricefile [format]')
103108

104109
main(sys.argv)
105110

Work/stock.py

Lines changed: 7 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,14 @@
11

2+
from typedproperty import String, Integer, Float
23

34
class Stock:
45

5-
__slots__ = ['name', '_shares', 'price'] # this is an optimization to save memory, but it also prevents adding new attributes to the class
6+
# __slots__ = ['name', '_shares', 'price'] # this is an optimization to save memory, but it also prevents adding new attributes to the class
7+
8+
name = String('name')
9+
shares = Integer('shares')
10+
price = Float('price')
11+
612

713
def __init__(self, name, shares, price):
814
self.name = name
@@ -15,19 +21,6 @@ def __init__(self, name, shares, price):
1521
def __repr__(self):
1622
return f"Stock({self.name}, {self.shares}, {self.price})"
1723

18-
# the shares property internally uses a private name, but the rest of the class can use the public name
19-
# goog.__dict__ gives: {'name': 'GOOG', '_shares': 100, 'price': 490.1}
20-
21-
@property
22-
def shares(self):
23-
return self._shares
24-
25-
@shares.setter
26-
def shares(self, shares):
27-
if not isinstance(shares, int) or shares < 0:
28-
raise ValueError('Shares must be non-negative integer')
29-
self._shares = shares
30-
3124

3225
@property
3326
def cost(self):

Work/typedproperty.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
2+
3+
def typedproperty(propa, expected_type):
4+
5+
private_propa = '_' + propa
6+
7+
@property
8+
def prop(self):
9+
return getattr(self, private_propa)
10+
11+
@prop.setter
12+
def prop(self, value):
13+
if not isinstance(value, expected_type) or (isinstance(value, (int, float)) and value < 0):
14+
raise TypeError(f'Expected {expected_type}')
15+
setattr(self, private_propa, value)
16+
17+
return prop
18+
19+
20+
21+
22+
String = lambda t_prop: typedproperty(t_prop, str)
23+
Integer = lambda t_prop: typedproperty(t_prop, int)
24+
Float = lambda t_prop: typedproperty(t_prop, float)
25+

Work/using_portfolio.py

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22
import report
33

44
portfolio = report.read_portfolio('.\\Data\\portfolio.csv')
5+
6+
57
print(len(portfolio))
68

79
print(portfolio[0])
@@ -12,9 +14,8 @@
1214
print('YIT' in portfolio)
1315

1416
print(portfolio.total_cost)
15-
print(portfolio.tabulate_shares())
16-
1717
holdings = portfolio.tabulate_shares()
18+
print(holdings)
1819

1920
print(holdings.most_common(2))
2021

@@ -23,6 +24,20 @@
2324

2425

2526

27+
def stock_name(s):
28+
return 1/s.price # reverse order
29+
30+
portfolio = list(portfolio)
31+
32+
portfolio.sort(key=stock_name)
33+
for s in portfolio:
34+
print(s)
35+
36+
print()
37+
38+
portfolio.sort(key=lambda s: s.price)
39+
for s in portfolio:
40+
print(s)
2641

2742
"""
2843
class Box:

Work/using_report.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import report as r
22
import stock
33

4-
4+
pf_file = '.\\Data\\portfolio.csv'
55
price_file = '.\\Data\\prices.csv'
66

77
# pf_files = ['.\\Data\\portfolio.csv', '.\\Data\\portfolio2.csv']
@@ -10,20 +10,24 @@
1010
# r.portfolio_report(file, price_file)
1111
# print()
1212

13-
pf_file = '.\\Data\\portfolio.csv'
1413

14+
# read portfolio and print it (just Portfolio object so nothing much to print)
1515
portfolio = r.read_portfolio(pf_file)
1616
print(portfolio)
1717

18+
# make default report with txt formatter
1819
print(f'{pf_file:-^43s}')
1920
r.portfolio_report(pf_file, price_file)
2021
print()
2122

23+
# html formatter
2224
r.portfolio_report(pf_file, price_file, 'html')
2325
print()
2426

27+
# and csv formatter
2528
r.portfolio_report(pf_file, price_file, 'csv')
2629
print()
2730

2831
# r.portfolio_report(pf_file, price_file, 'aku_ankka')
32+
# r.portfolio_report(pf_file)
2933

Work/using_stock.py

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -3,35 +3,36 @@
33
import stock
44

55

6-
a = stock.Stock('GOOG',100,490.10)
6+
a = stock.Stock('GOOG', 100, 490.10)
77

88
print(a) # Stock(GOOG, 100, 490.1)
9-
# print(a.__dict__) # {'name': 'GOOG', '_shares': 100, 'price': 490.1}
9+
print(a.__dict__) # {'name': 'GOOG', '_shares': 100, 'price': 490.1}
1010

11-
columns = ['name', 'shares']
12-
for colname in columns:
13-
print(colname, '=', getattr(a, colname))
11+
# columns = ['name', 'shares']
12+
# for colname in columns:
13+
# print(colname, '=', getattr(a, colname))
1414

1515

1616
b = stock.Stock('AAPL', 50, 122.34)
1717
c = stock.Stock('IBM', 75, 91.75)
1818

19-
print(b.shares * b.price)
19+
# print(b.shares * b.price)
2020

2121
stocks = [a, b, c]
22+
c.shares = 555
23+
c.price = 66.9
2224

25+
print(c)
2326

2427
for s in stocks:
2528
print(f'{s.name:>10s} {s.shares:>10d} {s.price:>10.2f}')
2629

27-
# print(a.cost())
2830
print(a.cost) # because cost is now a property, not a method
2931

30-
a.sell(25)
32+
# a.sell(25)
3133

32-
print(a.shares)
33-
# print(a.cost())
34-
print(a.cost)
34+
# print(a.shares)
35+
# print(a.cost)
3536

3637

3738

0 commit comments

Comments
 (0)