On Wed, May 08, 2019 at 12:18:34AM +1200, Greg Ewing wrote:
Steven D'Aprano wrote:
That suggests a possible pair of constructors:
bytes.from_int(n) -> equivalent to b'%d' % n bytes.ord(n) -> equivalent to bytes((n,))
I don't see how bytes.from_int(n) is any clearer about what it does than just bytes(n). If we're going to have named constructors, the names should indicate *how* the construction is being done, not just repeat the type of the argument.
Don't be shy, give us your suggested name. I'm not married to the suggestion of "from_int", if somebody with better skills at naming than me can come up with a short but descriptive name that would be great. But my other suggestion was going to be: bytes.return_bytes_representing_the_integer_input_as_an_ascii_bytestring() *wink* But seriously, its nice when a method of function name is completely self-explanatory, and some day I hope to find one which is. But until then, names are more like mnemonics: - dict.fromkeys returns a dict created from keys in what way? - str.encode encodes a string into what kind of data? - bytes.fromhex does what precisely? - what on earth is a glob? We say "import spam", not "import module spam and bind it to the name spam". We use "import" as a short name that, once we've learned what it does, reminds us what it does. It doesn't have to document every bit of functionality, just enough to associate the name with the semantics. In this case, the problem we are trying to solve is this: - convert an int like 12345 into a byte-string like b'12345'. Imagine you're looking at the dir(bytes) to find an appropriate method that perhaps does what you want, and you see methods like: - count - decode - fromhex - isdigit - split etc, plus the suggested "fromint". Which method are you going to associate with the problem you're trying to solve? -- Steven