PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, November 4, 2022

[FIXED] How to create an independent copy of a function in python?

 November 04, 2022     copy, deep-copy, function, lambda, python     No comments   

Issue

Is it possible in python to create an un-linked copy of a function? For example, if I have

a = lambda(x): x
b = lambda(x): a(x)+1

I want b(x) to always return x+1, regardless if a(x) is modified not. Currently, if I do

a = lambda(x): x
b = lambda(x): a(x)+1
print a(1.),b(1.)
a = lambda(x): x*0
print a(1.),b(1.)

the output is

1. 2.
0. 1.

Instead of being

1. 2.
0. 2.

as I would like to. Any idea on how to implement this? It seems that using deepcopy does not help for functions. Also keep in mind that a(x) is created externally and I can't change its definition. I've also looked into using this method, but it did not help.


Solution

You could define b like this:

b = lambda x, a=a: a(x)+1

This makes a a parameter of b, and therefore a local variable. You default it to the value of a in the current environment, so b will hold onto that value. You don't need to copy a, just keep its current value, so that if a new value is created, you have the one you wanted.

That said, this sounds like something unusual happening, and if you tell us more about what's going on, there's likely a better answer.



Answered By - Ned Batchelder
Answer Checked By - Katrina (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing