6

PyLint told me that one of my class methods didn't need to be a method, but could just be a function in a class since it didn't use any class attribute. That made me do things I thought were "bad," but maybe they are Pythonic. Is the following code what Python wants us to do?

class TestClass(ParentClass):
    def __init__(self):
        def callbackfunction(text):
            print("hello")
        ParentClass.map_event_to_callback(ParentClass.event, callbackfunction)

where ParentClass.event emits text to its callback, but we'll just ignore that print "hello" instead. Even simpler:

class TestClass():
    def __init__(self, text):
        def printhello(text):
            print("hello")
        printhello(text)

assuming I don't care about text or printhello after __init__.

3
  • 7
    Nope,that's fine. You could use a lambda too. Commented Mar 9, 2016 at 0:07
  • 2
    A function within a method is really no different from a function within an function. Sometimes it makes sense, and when it does, there's no reason not to use it. Commented Mar 9, 2016 at 0:24
  • Thank you, @MartijnPieters and @TomKarzes! Putting a callback function inside of a class' __init__ made me feel dirty, but I didn't know if there was a technical reason to avoid it or not. @MartijnPieters, if you make your comment an answer I can select it. Commented Mar 9, 2016 at 18:00

1 Answer 1

1

Creating a nested function for a callback is just fine. It even gives that function access to any locals in the parent function (as closures).

You can use a lambda if all you need to execute is one expression:

class TestClass(ParentClass):
    def __init__(self):
        ParentClass.map_event_to_callback(ParentClass.event, lambda text: print("hello"))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.