Skip to content

Commit

Permalink
Dyn methods: Change lambdas to functions
Browse files Browse the repository at this point in the history
Replace lambdas with function definitions. In a later commit, we will
switch to binding the function as a method to the class instead of to
the instance. In that process, we will be changing some of its
attributes, so then the function object needs to be assigned to a name.
A regular function `def` takes care of that assignment already.

Some other reasons:

- Using lambdas as class/instance methods is frowned upon. Error code
  E731 in flake8, for example. [[1]] [[2]]
- Easier to add docstrings to a function later. [[3]]
- Lambdas cannot contain statements. Here this stands in the way of
  replacing `__setitem__()` with a regular assignment later.

Lambdas return functions as well, so no changes in behavior are
expected [[4]] [[5]]. Timeit is not showing any significant changes in
performance.

The use of the same name (`func`) for these two short-lived functions
triggers pylint error `E0102`/`function-redefined`. Fixing this by
giving the functions two different names might actually increase the
risk of copy-paste bugs, while the redefining of the functions actually
still continues because we are in a loop. It is just that pylint will
not see it anymore then. I plan to discuss how this pylint error should
be addressed in the pull request containing this commit. For now, a
pragma is added to suppress it.

[1]: https://realpython.com/python-lambda/#python-classes
[2]: https://pycodestyle.pycqa.org/en/latest/intro.html#error-codes
[3]: f374f66
[4]: https://stackoverflow.com/questions/12264834/what-is-the-difference-for-python-between-lambda-and-regular-function
[5]: https://stackoverflow.com/questions/44840101/in-python-lambda-expression-is-fast-or-the-normal-function

(This commit is part of a series of changes in how the `get_*`,
`set_*`, `create_*` and `write_*` methods are dynamically created.)
  • Loading branch information
peternowee committed Feb 16, 2021
1 parent 4e41609 commit 4b75945
Showing 1 changed file with 6 additions and 6 deletions.
12 changes: 6 additions & 6 deletions pydot.py
Original file line number Diff line number Diff line change
Expand Up @@ -534,15 +534,15 @@ def create_attribute_methods(self, obj_attributes):

# Generate all the Setter methods.
#
setattr(self,
'set_'+attr,
lambda x, a=attr :
self.obj_dict['attributes'].__setitem__(a, x) )
def func(x, a=attr):
self.obj_dict['attributes'].__setitem__(a, x)
setattr(self, 'set_'+attr, func)

# Generate all the Getter methods.
#
setattr(self,
'get_'+attr, lambda a=attr : self.__get_attribute__(a))
def func(a=attr): # pylint: disable=function-redefined
return self.__get_attribute__(a)
setattr(self, 'get_'+attr, func)



Expand Down

0 comments on commit 4b75945

Please sign in to comment.