Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

I read somewhere that it is bad to define functions inside of functions in python, because it makes python create a new function object very time the outer 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()

Is this true? Also, what about a case when 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 I put all the constants inside the definition of f? Or should I leave them outside and bind them to local names in a keyword argument? I don't have any data to do timings with unfortunately, so I guess I'm asking about your experiences with similar things.

like image 397
Broseph Avatar asked Nov 03 '13 15:11

Broseph


People also ask

Which function is used to create an object in Python?

Note: The __init__() function is called automatically every time the class is being used to create a new object.

What is required to create an object in Python?

Creating an Object in Python The procedure to create an object is similar to a function call. This will create a new object instance named harry . We can access the attributes of objects using the object name prefix. Attributes may be data or method.

Which function is called when an object is created?

In class-based, object-oriented programming, a constructor (abbreviation: ctor) is a special type of subroutine called to create an object. It prepares the new object for use, often accepting arguments that the constructor uses to set required member variables.

When objects are created in Python?

Creating an Object of a Class in Python The object is created after creating a class. Instant of the object is created using the name same as the class name and it is known as Object Instantiation. One can give any name to a newly created object. Object creation is similar to calling a function.


1 Answers

Short answers to you questions - it is true. Inner functions are created each time outer function is called, and this takes some time. Also access to objects, which were defined outside of a function, is slower, comparing to access to local variables.

However, you also asked more important question - "should I care?". Answer to this, almost always, NO. Performance difference will be really minor, and readability of your code is much more valuable.

So, if you think that this function belongs to body of other function and makes no sense elsewhere - just put it inside and do not care about performance (at least, until your profiler tells you otherwise).

like image 160
Roman Bodnarchuk Avatar answered Oct 02 '22 21:10

Roman Bodnarchuk