How to create functions with a name of the list item,

257 views Asked by At

In kivy app on start it receives a json values assigns them to a variable and appends them to a list. On every App launch it receives a different values, therefore list is always different.

Ch1_name = channel.json()['items']['channels'][0]['channelName']
Ch2_name = channel.json()['items']['channels'][1]['channelName']
Ch3_name = channel.json()['items']['channels'][2]['channelName']
Ch4_name = channel.json()['items']['channels'][3]['channelName']

channels = []

channels.append(Ch1_name)
channels.append(Ch2_name)
channels.append(Ch3_name)
channels.append(Ch4_name)

print(channels)
['cnn','fox','sky sports','fsc']

Question: i need to create functions for each channel, that will preserve a name of a list item which is a channel name. Something like:

def cnn()
    print('this function was named cnn just like an item list')

Maybe there is a different way to do it with a class? Thank you for any ideas.

2

There are 2 answers

1
GProst On BEST ANSWER
for channel_name in channels:
  exec(f"""
def {channel_name}():
  print(f'this function was named {channel_name} just like an item list')
"""
  )
0
wholevinski On

You can do some metaprogramming stuff to add functions dynamically. Here's some sample code where it uses setattr to set functions on a class based on the name of the channel.

class ChannelPrinter:
    pass

channel_printer = ChannelPrinter()

for channel in ['cnn', 'fox', 'sky sports', 'fsc']:
    def make_func(name):
        def print_channel_info():
            print('this function was named {} just like an item list'.format(name))
        return print_channel_info

    setattr(channel_printer, channel, make_func(name=channel))

> channel_printer.cnn()
this function was named cnn just like an item list
> channel_printer.fox()
this function was named fox just like an item list