Reputation: 722
i've found this code on the man page of amazon. It is used as a to create callback objects that can be passed as argument of the upload function of the transfer module:
class ProgressPercentage(object):
def __init__(self, filename):
self._filename = filename
self._size = float(os.path.getsize(filename))
self._seen_so_far = 0
self._lock = threading.Lock()
def __call__(self, bytes_amount):
# To simplify we'll assume this is hooked up
# to a single filename.
with self._lock:
self._seen_so_far += bytes_amount
percentage = (self._seen_so_far / self._size) * 100
sys.stdout.write(
"\r%s %s / %s (%.2f%%)" % (
self._filename, self._seen_so_far, self._size,
percentage))
sys.stdout.flush()
a class is used to retain the state necessary for the subsequent calls (self.seen_so_far i.e.)
is there a way to reimplement this as a function taking advantage of python closure to ensure statefulness ?
Upvotes: 0
Views: 1233
Reputation: 96246
Sure, a straightforward transliteration would be something like:
def ProgressPrecentage(filename):
size = os.path.getsize(filename)
seen_so_far = 0
lock = threading.Lock()
def worker(bytes_amount):
nonlocal seen_so_far
with lock:
seen_so_far += bytes_amount
percentage = (seen_so_far / size)*100
msg = "\r%s %s / %s (%.2f%%)" % (
filename, seen_so_far, size, percentage
)
sys.stdout.write(msg)
sys.stdout.flush()
return worker
Upvotes: 2