简体   繁体   English

如何优化回调python代码以获得更好的可读性和pythonic实践?

[英]How to optimize the callback python code for better readability and pythonic practice?

I have a private function that needs to be invoked from the constructor.我有一个需要从构造函数调用的私有函数。 This private function's job is to do the subscription for the events that will be notified by an external program.这个私有函数的工作是订阅外部程序通知的事件。 All the subscription functions need generic parameters like freq, initialPublication, initiallySuspended, callback and asynchronous.所有订阅函数都需要通用参数,如 freq、initialPublication、initialSuspended、回调和异步。 I want all the subscription parameters to be the same.我希望所有订阅参数都相同。 However, the callback should vary.但是,回调应该有所不同。 Here is the generic params dictionary I have created.这是我创建的通用参数字典。

params = {'freq': 0, 'initialPublication': True,

                      'initiallySuspended': False, 'callback': None,

                      'asynchronous':   True,

                      }

                  

I have added a comment where I feel pretty repetitive ie我添加了一个评论,我觉得很重复,即

params[callback] = self.callback_test_sub1
 subscribe_attrib = 'subscribe_testSub1'
 if not self._subscribe(params, subscribe_attrib):
            return False
 ......
 

What can I do to improve this or is it already in its best form?我可以做些什么来改善这一点,或者它是否已经处于最佳状态?

class Test:
    
    def callback_test_sub1(self, sub1_data):
        print('got sub1 data')
        
    def callback_test_sub2(self, sub2_data):
        print('got sub2 data')
        
    def notify_test_sub3(self, sub3_data):
        print('got sub3 data')
        
    def _subscribe(self, params, subscribe_attribute):
        try:
            func = getattr(self.external_obj, subscribe_attribute)
            err_status = func(**params)
        except AttributeError:
            print('no such attribute')

        except Exception as e:
            print(e)
    
    def __init__(self):
        params = {'freq': 0, 'initialPublication': True,
        'initiallySuspended': False, 'callback': None, 'asynchronous': True}
        
        ###  while doing these 3 callbacks, I feel repetitive
        params[callback] = self.callback_test_sub1
        subscribe_attrib = 'subscribe_testSub1'
        if not self._subscribe(params, subscribe_attrib):
            return False
        params[callback] = self.callback_test_sub2
        subscribe_attrib = 'subscribe_testSub2'
        if not self._subscribe(params, subscribe_attrib):
            return False
        params[callback] = self.callback_test_sub2
        subscribe_attrib = 'subscribe_testSub3'
        if not self._subscribe(params, notify_test_sub3):
            return False
        ###  while doing these 3 callbacks, I feel repetitive end
        return True

If you don't want to repeat these small blocks, you could make a list through which to iterate:如果你不想重复这些小块,你可以制作一个列表来迭代:

callbacks = (('subscribe_testSub1', self.callback_test_sub1), 
             ('subscribe_testSub2', self.callback_test_sub2), 
             ('subscribe_testSub3', self.callback_test_sub3))
for attribute, callback in callbacks:
    params['callback'] = callback
    if not self._subscribe(params, attribute)
        return False

Given that your code example already shows several typos/errors, it might be actually useful to reduce this repetition.鉴于您的代码示例已经显示了几个拼写错误/错误,减少这种重复实际上可能很有用。 If the callback and attribute names have a specific pattern, you could also compute them and retrieve with getattr , but the code might get more obscure then and cannot be verified statically.如果回调和属性名称具有特定模式,您还可以计算它们并使用getattr检索,但代码可能会变得更加晦涩,无法静态验证。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM