python, confused in decorate and closure

2024/11/14 15:37:57

I have some test code:

def num(num):def deco(func):def wrap(*args, **kwargs):inputed_num = numreturn func(*args, **kwargs)return wrapreturn deco@num(5)
def test(a):return a + inputed_numprint test(1)

when run this code, I got an error shows that 'inputed_num' is not defined

My question is: In wrap function, is there not a closure that func can got 'inputed_num' ?

Anyway, If not, how should I do to got my aim: Initialize some value, and use this value directly in the main function.

Thinks.

Answer

No, there isn't a closure like that. Functions can close over variables that are present in the surrounding lexical context, not in the calling context. In other words, if you actually write one function in another, then the inner one can have access to variables in the outer one:

def f():g = 2def f2():print gf2()

But functions never have access to variables inside the function that called them.

In general there isn't a way to do what you want, viz., set an arbitrary variable in a function from outside the function. The closest thing is you could use a global inputed_num in your decorator to assign inputed_num as a global variable. Then test would access the global value.

def num(num):def deco(func):def wrap(*args, **kwargs):global outsideroutsider = numreturn func(*args, **kwargs)return wrapreturn deco
@num(5)
def test(a):print a+outsider>>> test(2)
7

But of course the variable setting is then global, so multiple concurrent uses (e.g., recursion) wouldn't work. (Just for fun, you can also see here for a very arcane way to do this, but it is way too crazy to be useful in a real-world context.)

https://en.xdnf.cn/q/72032.html

Related Q&A

Python Regex - checking for a capital letter with a lowercase after

I am trying to check for a capital letter that has a lowercase letter coming directly after it. The trick is that there is going to be a bunch of garbage capital letters and number coming directly befo…

Read hierarchical (tree-like) XML into a pandas dataframe, preserving hierarchy

I have a XML document that contains a hierarchical, tree-like structure, see the example below.The document contains several <Message> tags (I only copied one of them for convenience).Each <Me…

Reference counting using PyDict_SetItemString

Im wondering how memory management/reference counting works when a new value is set into an existing field within a PyDict (within a C extension).For instance, assume a dictionary is created and popula…

How to use statsmodels.tsa.seasonal.seasonal_decompose with a pandas dataframe

from statsmodels.tsa.seasonal import seasonal_decomposedef seasonal_decomp(df, model="additive"):seasonal_df = Noneseasonal_df = seasonal_decompose(df, model=additive)return seasonal_dfseason…

UnidentifiedImageError: cannot identify image file

Hello I am training a model with TensorFlow and Keras, and the dataset was downloaded from https://www.microsoft.com/en-us/download/confirmation.aspx?id=54765 This is a zip folder that I split in the …

Pydub raw audio data

Im using Pydub in Python 3.4 to try to detect the pitch of some audio files.I have a working pitch detection algorithm (McLeod Pitch Method), which is robust for real-time applications (I even made an …

Create Duplicate Rows and Change Values in Specific Columns

How to create x amount of duplicates based on a row in the dataframe and change a single or multi variables from specific columns. The rows are then added to the end of the same dataframe.A B C D E F 0…

writing and saving CSV file from scraping data using python and Beautifulsoup4

I am trying to scrape data from the PGA.com website to get a table of all of the golf courses in the United States. In my CSV table I want to include the Name of the golf course ,Address ,Ownership ,We…

Performance issue turning rows with start - end into a dataframe with TimeIndex

I have a large dataset where each line represents the value of a certain type (think a sensor) for a time interval (between start and end). It looks like this: start end type value 2015-01-01…

How can I create a key using RSA/ECB/PKCS1Padding in python?

I am struggling to find any method of using RSA in ECB mode with PKCS1 padding in python. Ive looked into pyCrypto, but they dont have PKCS1 padding in the master branch (but do in a patch). Neverthel…