Empty function object in python

I heard that python functions are objects similar to lists or dictionaries, etc. However, what would be a similar way to perform this type of action with a function?

# Assigning empty list to 'a'
a = list()

# Assigning empty function to 'a'
a = lambda: pass
# ???

How do you do this? Also, is this necessary or correct? Here is the point in which I would like to use it for a better context:

I have QListWidgetto select items related to keys in a dictionary. The values ​​in this dictionary are also dictionaries that contain certain properties of the elements that I can add. These specific properties are stored as keys, and the values ​​in them are initialized or updated, invoking various functions. So, I save the variable in the window, which is updated when the button is clicked, to inform the script property that needs to be updated.

As you can see, I would like to save a function for matching data using the correct function depending on the situation.

# Get selection from the list
name = selected_item
# Initialize an empty function
f = lambda: pass
# Use property that is being added now, which was updated by the specific button that was pushed
property_list = items[name][self.property_currently_being_added]
if self.property_currently_being_added == "prop1":
    f = make_property1()
elif self.property_currently_being_added == "prop2":
    f = make_property2()
elif self.property_currently_being_added == "prop3":
    f = make_property3()
elif self.property_currently_being_added == "prop4":
    f = make_property4()

# map the certain function to the data which was retrieved earlier
added_property = map(f, data)
property_list.append(added_property)
+4
source share
2 answers

Firstly, the reason this does not work:

a = lamdba: pass

... , lambda , . pass , , .

:

a = lambda: None

Python , return, None. , :

def a(): return None
def a(): pass

, ; def (a <lambda>) .. - lambda - , , . , , lambda . def.


, " " , , ( , , dis.dis(a)), , , return None), . " ". a map, TypeError, . ( , map.)

, , - , as-is. :

def a(x): return x

, . data - ? - , , , ...?


, , . map, ? else, ( , ...). , , f = None, if f:, , . , :

added_property = [f(element) if f else element for element in data]

... ...

added_property = map(f, data) if f else data

, if/elif, , dict:

propfuncs = {'prop1': make_property1(),
             'prop2': make_property2(),
             'prop3': make_property3(),
             'prop4': make_property4()}

:

f = propfuncs.get(self.property_currently_being_added)
added_property = map(f, data) if f else data

, , make_propertyN , make_property(1) make_property('prop1')... , , .

+13

, Nothing, , Monads, , PyMonad Nothing, , .

0

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


All Articles