Are immutable arrays possible in .NET?

The Framework Design Guidelines suggest returning a copy of the Array. That way, consumers can’t change items from the array. // bad code // could still do Path.InvalidPathChars[0] = ‘A’; public sealed class Path { public static readonly char[] InvalidPathChars = { ‘\”‘, ‘<‘, ‘>’, ‘|’ }; } these are better: public static ReadOnlyCollection<char> GetInvalidPathChars(){ … Read more

Pandas: Modify a particular level of Multiindex

Thanks to @cxrodgers’s comment, I think the fastest way to do this is: df.index = df.index.set_levels(df.index.levels[0].str.replace(‘ ‘, ”), level=0) Old, longer answer: I found that the list comprehension suggested by @Shovalt works but felt slow on my machine (using a dataframe with >10,000 rows). Instead, I was able to use .set_levels method, which was quite … Read more

final fields and thread-safety

In order to use an effectively immutable object without final fields in a thread safe manner you need to use one of safe publication idioms when making the object available to other threads after initialization, otherwise these threads can see the object in partially initialized state (from Java Concurrency in Practice): Initializing an object reference … Read more

Python, subclassing immutable types

Yes, you need to override __new__ special method: class MySet(frozenset): def __new__(cls, *args): if args and isinstance (args[0], basestring): args = (args[0].split (),) + args[1:] return super (MySet, cls).__new__(cls, *args) print MySet (‘foo bar baz’) And the output is: MySet([‘baz’, ‘foo’, ‘bar’])

Immutable type and property in C#

An immutable type is a type of which its properties can only be set at initialization. Once an object is created, nothing can be changed anymore. An immutable property is simply a read-only property. In the following example, ImmutableType is an immutable type with one property Test. Test is a read-only property. It can only … Read more