I'm new in python and I'm wondering if there any issue I should worry about in the following code?
from base64 import b64encode
class Base64Encoder:
@classmethod
def encode_basic(cls, usr, pwd):
token = cls.base64_encode(f"{usr}:{pwd}")
return f'Basic {token}'
@classmethod
def encode_bearer(cls, token):
return f'Bearer {token}'
@staticmethod
def base64_encode(token):
return b64encode(token.encode('ascii')).decode('ascii')
1 Answer 1
You've got a class with only two classmethod
s and one staticmethod
. One classmethod
does not use the class argument, the other one refers to a static method. Hence none of the class' methods use either the class or one of its instances. Thus, you do not require a class at all:
def encode_basic(usr, pwd):
token = base64_encode(f"{usr}:{pwd}")
return f'Basic {token}'
def encode_bearer(token):
return f'Bearer {token}'
def base64_encode(token):
return b64encode(token.encode('ascii')).decode('ascii')
Also consider adding docstrings to the functions, that explain how they are supposed to be used. Without knowlege of your program's context it is hard to tell, why the strings are being formatted in the respective ways and why one string needs ASCII encoding.
-
\$\begingroup\$ thanks for the recommendation. What if I use those methods in many places and I don't want to duplicate it in each place? That's why I create a class \$\endgroup\$indigo153– indigo1532018年07月23日 10:01:35 +00:00Commented Jul 23, 2018 at 10:01
-
1\$\begingroup\$ You can re-use functions just like classes. Both can be imported by other modules. \$\endgroup\$Richard Neumann– Richard Neumann2018年07月23日 10:02:25 +00:00Commented Jul 23, 2018 at 10:02
encode_bearer()
? \$\endgroup\$