Python function in multidimensional dictionary

def func():
    something

d = { 'func': func }
d['func']() # callable

d2 = { 'type': { 'func': func } }
d2['type']['func']() # not callable

d3 = { 'type': { 'func': func() } }
d3['type']['func']() # callable

What is the difference between d and d2?

Why is d3 not callable and d2 not callable?

this code is executable, but pycham allocates d2'func 'and says that the dict object cannot be called

+4
source share
1 answer

Defining a function in python will make it callable. What it does after completion will only matter if you actually call it (using the () operator). Without defining a return statement, the function will return None. As described here: Python - return, return None, and return in general .

, func, - . , pycharm . d d2 , d3 . func d3, , d3 .

Python 2.7.12 (default, Oct 10 2016, 12:50:22)
[GCC 5.4.0] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
dlopen("/usr/lib/python2.7/lib-dynload/readline.dll", 2);
import readline # dynamically loaded from /usr/lib/python2.7/lib-dynload/readline.dll
>>>
>>> def func():
...     something
...
>>> d = { 'func': func }
>>> d['func']()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in func
NameError: global name 'something' is not defined
>>>
>>> d2 = { 'type': { 'func': func } }
>>> d2['type']['func']()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in func
NameError: global name 'something' is not defined
>>>
>>> d3 = { 'type': { 'func': func() } }
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in func
NameError: global name 'something' is not defined
>>> d3['type']['func']()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'd3' is not defined
0

Source: https://habr.com/ru/post/1662598/


All Articles