When a function is used in python, what objects need to be created?

I read somewhere that it is bad to define functions inside functions in python because it forces python to create a new function object very often when an external function is called. Someone basically said this:

#bad
def f():
    def h():
        return 4
return h()

#faster
def h():
    return 4

def f(h=h):
    return h()

It's true? Also, for the case where I have a ton of constants like this:

x = # long tuple of strings
# and several more similar tuples
# which are used to build up data structures

def f(x):
    #parse x using constants above
    return parse dictionary

Is it faster if you put all the constants in the definition of f? Or should I leave them outside and bind them to local names in the keyword argument? Unfortunately, I do not have data for timings, therefore, I think, I ask about your experience with similar things.

+4
source share
3 answers

, , , , , , . dis.dis, cProfile.run timeit.timeit , script .

0

- . , , . , , , .

: " ?". , , . , .

, , - ( , ).

+5

, , , . , , : , Python. , , , , , Python , () , .

, , -, x f, , .

, , . , , . , , , . ( ), , , .

, . . , - / ( ).

, , , , . , .

In general, however, it is more likely to be micro-optimization, and you are unlikely to encounter any problems if you do this in one or another way. So Id suggests you write clear code first and make sure everything else works well, and if you really run into performance issues later, you can check where the problems are.

0
source

All Articles