Deep copying a PSObject

Note that here is a shorter, maybe a bit cleaner version of this (that I quite enjoy): $data = Import-Csv .\test.csv $serialData = [System.Management.Automation.PSSerializer]::Serialize($data) $data2 = [System.Management.Automation.PSSerializer]::Deserialize($serialData) Note: However, weirdly, it does not keep the ordering of ordered hashtables. $data = [ordered] @{ 1 = 1 2 = 2 } $serialData = [System.Management.Automation.PSSerializer]::Serialize($data) $data2 = … Read more

How to create a copy of a python function [duplicate]

In Python3: import types import functools def copy_func(f): “””Based on http://stackoverflow.com/a/6528148/190597 (Glenn Maynard)””” g = types.FunctionType(f.__code__, f.__globals__, name=f.__name__, argdefs=f.__defaults__, closure=f.__closure__) g = functools.update_wrapper(g, f) g.__kwdefaults__ = f.__kwdefaults__ return g def f(arg1, arg2, arg3, kwarg1=”FOO”, *args, kwarg2=”BAR”, kwarg3=”BAZ”): return (arg1, arg2, arg3, args, kwarg1, kwarg2, kwarg3) f.cache = [1,2,3] g = copy_func(f) print(f(1,2,3,4,5)) print(g(1,2,3,4,5)) print(g.cache) assert … Read more

JS: Does Object.assign() create deep copy or shallow copy

Forget about deep copy, even shallow copy isn’t safe, if the object you’re copying has a property with enumerable attribute set to false. MDN : The Object.assign() method only copies enumerable and own properties from a source object to a target object take this example var o = {}; Object.defineProperty(o,’x’,{enumerable: false,value : 15}); var ob={}; … Read more

How to create a deep copy of an object in Ruby?

Deep copy isn’t built into vanilla Ruby, but you can hack it by marshalling and unmarshalling the object: Marshal.load(Marshal.dump(@object)) This isn’t perfect though, and won’t work for all objects. A more robust method: class Object def deep_clone return @deep_cloning_obj if @deep_cloning @deep_cloning_obj = clone @deep_cloning_obj.instance_variables.each do |var| val = @deep_cloning_obj.instance_variable_get(var) begin @deep_cloning = true val … Read more

Deep copy of List

The idiomatic way to approach this in C# is to implement ICloneable on your Data, and write a Clone method that does the deep copy (and then presumably a Enumerable.CloneRange method that can clone part of your list at once.) There isn’t any built-in trick or framework method to make it easier than that. Unless … Read more

How do I copy a hash in Ruby?

The clone method is Ruby’s standard, built-in way to do a shallow-copy: irb(main):003:0> h0 = {“John” => “Adams”, “Thomas” => “Jefferson”} => {“John”=>”Adams”, “Thomas”=>”Jefferson”} irb(main):004:0> h1 = h0.clone => {“John”=>”Adams”, “Thomas”=>”Jefferson”} irb(main):005:0> h1[“John”] = “Smith” => “Smith” irb(main):006:0> h1 => {“John”=>”Smith”, “Thomas”=>”Jefferson”} irb(main):007:0> h0 => {“John”=>”Adams”, “Thomas”=>”Jefferson”} Note that the behavior may be overridden: This … Read more