Using classes for this seems like a good idea, since you end up with a number of class instances, where each one represents a specific torrent.
In terms of the specific code, you're doing things slightly wrong in 2 ways.
Firstly, you don't need to pass instance parameters into the methods of a class. So you can access info
and file
as self.info
and self.file
, so your methods only need the self
argument.
Secondly, I can see that you're doing this to try to cache the results of the method calls by overriding the methods in __init__
, and while caching is good, this is a bad way of trying to achieve it.
There are 2 alternatives that spring to mind, depending on what you want to do:
If you always want the size and hash calculated when the class is instantiated, then do something similar to what you're doing now, but use different names for the data variables and the methods:
def __init__(self, torrentfile):
self.metainfo = bencode.bdecode(torrentfile.read())
self.info = self.metainfo['info']
self.files = self.metainfo['info']['files']
self.md5hash = self.calculate_md5hash()
self.size = self.calculate_size()
def calculate_md5hash(self):
return hashlib.sha1(bencode.bencode(self.info)).hexdigest()
def calculate_size(self):
filesize = 0
for file in self.files:
filesize += file['length']
return filesize
Alternatively, if you only want the hash and size calculated when the methods are specifically called, but you also want caching, use lru_cache
lru_cache
will cache the result of a function the first time it is run, and then simply return the result for future calls, providing the arguments to the function remain the same.
from functools import lru_cache
class Torrent(object):
def __init__(self, torrentfile):
self.metainfo = bencode.bdecode(torrentfile.read())
self.info = self.metainfo['info']
self.files = self.metainfo['info']['files']
@lru_cache()
def md5hash(self):
return hashlib.sha1(bencode.bencode(self.info)).hexdigest()
@lru_cache()
def size(self):
filesize = 0
for file in self.files:
filesize += file['length']
return filesize
Then call the methods explicitly:
print(torrentfile.md5hash())
print(torrentfile.size())