`method .__ name__ in dir (cls)` в моей записной книжке jupyter работает иначе, чем пакет ray - PullRequest
0 голосов
/ 29 января 2019

Только что обнаружил, что эта проблема возникает только в моей лаборатории jupyter.Этот же сценарий без проблем проходит проверку при выполнении в оболочке ubuntu bash.


Проверка переопределения класса if method.__name__ not in dir(cls): raise NameError не вызывается при импорте из установленного пакета, но повышается при копировании кода в локальный каталоги импортировать из локального ядра jupyer-lab.

Я использую ray-0.6.2 и пытаюсь настроить некоторые коды из ray.rllib.Поэтому я скопировал некоторые целевые коды на свой локальный компьютер и импортировал модули из локального.Метод copy модуля ray.rllib.agents.ppo.ppo_policy_graph.PPOPolicyGraph проверяет, переопределяет ли он абстрактный метод ray.rllib.evaluation.tf_policy_graph.TFPolicyGraph, с помощью следующей проверки декоратора

def override(cls):
    """Annotation for documenting method overrides.

    Arguments:
        cls (type): The superclass that provides the overriden method. If this
            cls does not actually have the method, an error is raised.
    """

    def check_override(method):
        if method.__name__ not in dir(cls):
            raise NameError("{} does not override any method of {}".format(
                method, cls))
        return method

    return check_override

Проверка проходит, когда я импортирую модуль из пакета, так чтоray.rllib.agents.ppo.ppo_policy_graph.PPOPolicyGraph, но возникает, когда я скопировал точные соответствующие коды и импортировал из локального: my.localpath.agents.ppo.ppo_policy_graph.PPOPolicyGraph.

Я обнаружил, что dir(TFPolicyGraph) не включает абстрактный метод copy name в моем ядре jupyter-lab,Я понимаю, что dir() не гарантирует отображение всех имен методов.Однако мне интересно, как это работает без проблем при импорте из установленного пакета.

Ниже приведены результаты трассировки и pdb.

Traceback (most recent call last):
  File "<ipython-input-17-880dd2fa265a>", line 3, in <module>
    from xray.agents.ppo.ppo_policy_graph import PPOPolicyGraph
  File "/home/kyu/Projects/x_ray/xray/agents/ppo/ppo_policy_graph.py", line 95, in <module>
    class PPOPolicyGraph(LearningRateSchedule, TFPolicyGraph):
  File "/home/kyu/Projects/x_ray/xray/agents/ppo/ppo_policy_graph.py", line 256, in PPOPolicyGraph
    @override(TFPolicyGraph)
  File "/home/kyu/anaconda3/envs/ray-tutorial/lib/python3.6/site-packages/ray/rllib/utils/annotations.py", line 17, in check_override
    method, cls))
NameError: <function PPOPolicyGraph.copy at 0x7fbdb07ae6a8> does not override any method of <class 'ray.rllib.evaluation.tf_policy_graph.TFPolicyGraph'>
> /home/kyu/anaconda3/envs/ray-tutorial/lib/python3.6/site-packages/ray/rllib/utils/annotations.py(17)check_override()
-> method, cls))
(Pdb)  p cls
<class 'ray.rllib.evaluation.tf_policy_graph.TFPolicyGraph'>
(Pdb)  p dir(cls)
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_get_is_training_placeholder', '_get_loss_inputs_dict', 'apply_gradients', 'build_apply_gradients', 'build_compute_actions', 'build_compute_apply', 'build_compute_gradients', 'compute_actions', 'compute_apply', 'compute_gradients', 'compute_single_action', 'extra_apply_grad_feed_dict', 'extra_apply_grad_fetches', 'extra_compute_action_feed_dict', 'extra_compute_action_fetches', 'extra_compute_grad_feed_dict', 'extra_compute_grad_fetches', 'get_initial_state', 'get_state', 'get_weights', 'gradients', 'loss_inputs', 'on_global_var_update', 'optimizer', 'postprocess_trajectory', 'set_state', 'set_weights']
(Pdb)  p [c for c in dir(cls) if c.startswith('c')]
['compute_actions', 'compute_apply', 'compute_gradients', 'compute_single_action']
(Pdb)  l
 12         """
 13     
 14         def check_override(method):
 15             if method.__name__ not in dir(cls):
 16                 raise NameError("{} does not override any method of {}".format(
 17  ->                 method, cls))
 18             return method
 19     
 20         return check_override
[EOF]
(Pdb)  p method
<function PPOPolicyGraph.copy at 0x7fbdb07ae6a8>
(Pdb)  p method.__name__
'copy'
(Pdb)  dir(cls)
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_get_is_training_placeholder', '_get_loss_inputs_dict', 'apply_gradients', 'build_apply_gradients', 'build_compute_actions', 'build_compute_apply', 'build_compute_gradients', 'compute_actions', 'compute_apply', 'compute_gradients', 'compute_single_action', 'extra_apply_grad_feed_dict', 'extra_apply_grad_fetches', 'extra_compute_action_feed_dict', 'extra_compute_action_fetches', 'extra_compute_grad_feed_dict', 'extra_compute_grad_fetches', 'get_initial_state', 'get_state', 'get_weights', 'gradients', 'loss_inputs', 'on_global_var_update', 'optimizer', 'postprocess_trajectory', 'set_state', 'set_weights']
...