Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a Python function stored as an object? [closed]

Tags:

python

This query is in continuation with link to understand further on this point:

In the case of functions, you have an object which has certain fields, which contain e. g. the code in terms of bytecode, the number of parameters it has, etc.

My question:

1) How do i visualise a function being represented as an object?(NPE answered this question here)

2) How do i visualise an higher order function being represented as an object?

3) How do i visualise modules being represented as an object? say 'import operator'

4) Are operators like '+' '>' '!=' '==' '=' are also mapped to some object methods? say for expr 'check = 2 < 3', Does this internally call some method of type(2) or type(3) to evaluate '<' operator?

like image 553
overexchange Avatar asked Dec 29 '25 19:12

overexchange


1 Answers

All this is saying is that, in Python, functions are objects like any other.

For example:

In [5]: def f(): pass

Now f is an object of type function:

In [6]: type(f)
Out[6]: function

If you examine it more closely, it contains a whole bunch of fields:

In [7]: dir(f)
Out[7]: 
['__call__',
 ...
 'func_closure',
 'func_code',
 'func_defaults',
 'func_dict',
 'func_doc',
 'func_globals',
 'func_name']

To pick one example, f.func_name is the function's name:

In [8]: f.func_name
Out[8]: 'f'

and f.func_code contains the code:

In [9]: f.func_code
Out[9]: <code object f at 0x11b5ad0, file "<ipython-input-5-87d1450e1c01>", line 1>

If you are really curious, you can drill down further:

In [10]: dir(f.func_code)
Out[10]: 
['__class__',
 ...
 'co_argcount',
 'co_cellvars',
 'co_code',
 'co_consts',
 'co_filename',
 'co_firstlineno',
 'co_flags',
 'co_freevars',
 'co_lnotab',
 'co_name',
 'co_names',
 'co_nlocals',
 'co_stacksize',
 'co_varnames']

and so on.

(The above output was produced using Python 2.7.3.)

like image 86
NPE Avatar answered Dec 31 '25 08:12

NPE



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!