diff --git a/strings.html b/strings.html index 796b4b2..7130a58 100644 --- a/strings.html +++ b/strings.html @@ -153,8 +153,45 @@ def approximate_size(size, a_kilobyte_is_1024_bytes=True):
>>> import humansize ->>> +>>> si_suffixes = humansize.SUFFIXES[1000] ① +>>> si_suffixes +['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'] +>>> "1000{0[0]} = 1{0[1]}".format(si_suffixes) ② +'1000KB = 1MB'+
humansize module, you'll just grab one of the data structures it defines: the list of "SI" (powers-of-1000) suffixes.
+{0} would refer to the first argument passed to the format() method, si_suffixes. But si_suffixes is a list. So {0[0]} refers to the first item of the list which is the first argument passed to the format() method: 'KB'. Meanwhile, {1[0]} refers to the second item of the same list: 'MB'. Everything outside the curly braces — including 1000, the equals sign, and the spaces — is untouched. The final result is the string '1000KB = 1MB'.
+What this example shows is that format specifers can access items and properties of data structures using (almost) Python syntax. The following things "just work": + +
Just to blow your mind, here's an example that combines all of the above: + +
+>>> import humansize
+>>> import sys
+>>> "1MB = 1000{0.modules[humansize].SUFFIXES[1000][0]}".format(sys)
+'1MB = 1000KB'
+
+Here's how it works: + +
sys module holds information about the currently running Python instance. Since you just imported it, you can pass the sys module itself as an argument to the format() method. So the format specifier {0} refers to the sys module.
+sys.modules is a dictionary of all the modules that have been imported in this Python instance. The keys are the module names as strings; the values are the module objects themselves. So the format specifier {0.modules} refers to the dictionary of imported modules.
+sys.modules["humansize"] is the humansize module which you just imported. The format specifier {0.modules[humansize]} refers the humansize module. Note the slight difference in syntax here. In real Python code, the keys of the sys.modules dictionary are strings; to refer to them, you need to put quotes around the module name (e.g. "humansize"). But within a format specifier, you skip the quotes around the dictionary key name (e.g. humansize).
+sys.modules["humansize"].SUFFIXES is the dictionary defined at the top of the humansize module. The format specifier {0.modules[humansize].SUFFIXES} refers to that dictionary.
+sys.modules["humansize"].SUFFIXES[1000] is a list of SI suffixes: ['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']. So the format specifier {0.modules[humansize].SUFFIXES[1000]} refers to that list.
+sys.modules["humansize"].SUFFIXES[1000][0] is the first item of the list of SI suffixes: 'KB'. Therefore, the complete format specifier {0.modules[humansize].SUFFIXES[1000][0]} is replaced by the two-character string KB.
+Note that (k, v) is a tuple. I told you they were good for something.