0

I would like to write a function to build a bytes type string that need to use f-string with different value. the only way I can think about is like following code. anyone have better suggestion? In code, I have string like I have level but in my actual code the string is about 600 charactors

def get_level_string(x):
    size = dict(v1=1, v2= 200, v3= 30000)
    s = size.get('v1')
    name = lambda x: f"I have level value as {x} in the house"
    return {
            'level1': b'%a' % (name(size['v1'])),
            'level2': b'%a' % (name(size['v2'])),
            'level3': b'%a' % (name(size['v3'])),
            }[x]

a = get_level_string('level1')
b = get_level_string('level2')
c = get_level_string('level3')
print(a, type(a))
print(b, type(b))
print(c, type(c))
=> #b"'I have level value as 1 in the house'" <class 'bytes'>
=> #b"'I have level value as 200 in the house'" <class 'bytes'>
=> #b"'I have level value as 30000 in the house'" <class 'bytes'>
jacobcan118
  • 7,797
  • 12
  • 50
  • 95
  • 1
    Why not just `.encode()` the string? e.g. `lambda x: f" ... {x} ...".encode()` and then you just have `'level': name(size['v1'])` – AChampion Aug 10 '18 at 18:00

1 Answers1

1

You can make this a good deal simpler, by generating the strings and then calling their encode method to make them bytes objects. Note that your function really just builds a dictionary and then looks stuff up in it. It's much simpler to build the dictionary only once and then supply the bound __getitem__ method under a different name.

template = "I have level value as {} in the house"
size_list = (1, 200, 30000)
sizes = {f"level{i}": template.format(x).encode() for i, x in enumerate(size_list, start=1)}
get_level_string = sizes.__getitem__


# tests
a = get_level_string('level1')
b = get_level_string('level2')
c = get_level_string('level3')
print(a, type(a))
print(b, type(b))
print(c, type(c))

prints

b'I have level value as 1 in the house' <class 'bytes'>
b'I have level value as 200 in the house' <class 'bytes'>
b'I have level value as 30000 in the house' <class 'bytes'>

for your tests

Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96
  • thx, but i should mention by output is not necessary in that sequence. update my question – jacobcan118 Aug 10 '18 at 18:07
  • @jacobcan118 I'm afraid I don't understand. Do you mean that the various `leveln` in your code are actually unrelated 600 character strings? – Patrick Haugh Aug 10 '18 at 18:13
  • i mean my output is not necessary to be level1 to level3, it maybe get_level_string('level2'), get_level_string('level3'), get_level_string('level1') in random sequence – jacobcan118 Aug 10 '18 at 18:17
  • @jacobcan118 I still don't see the issue. `__getitem__` doesn't affect the underlying dictionary, so i shouldn't matter what order you're calling them in. – Patrick Haugh Aug 10 '18 at 18:19