简体   繁体   中英

Python style question. Nested functions vs globally scoped functions

Python style question here. Is it generally cleaner/better to nest functions, or define them in the wider scope and access with self.function()?

For example, would it be better to write code like this:

class Blah:
    def doStuff(self, x, y):

        def doOtherStuff(a, b):
            return a

        return doOtherStuff(x, y)

or like this?:

class Blah:
    def doStuff(self, x, y):
        return self.doOtherStuff(x, y)

    def doOtherStuff(self, a, b):
            return a

Ask yourself how often you use doOtherStuff . Is it just within doStuff ? If so, nesting is fine, especially if it's just a few lines. If it's several lines of code, you may want to put it as a separate function to help readability ("Readability counts", The Zen of Python). Moreover, if you need to return doOtherStuff , then nesting is probably better.

Also, I'd add that you should use the convention of a single underscore prefix for a protected method and a double underscore ("dunder") prefix for a private method, if you choose to go the route of a separate method and if you don't use doOtherStuff outside the class.

Overall, use your best judgement for clarity. Without further details, it's difficult to recommend a method beyond these guidelines.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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