Living in the Tech Avalanche Generation

A practitioner’s introspective on technology

Archive for the 'C#' Category

C# classes for Mixins and Multiple Inheritance with IronPython

Question: Does IronPython support Multiple Inheritance / Mixins?

Ans: Yes!

Question: Can I use my C# classes from IronPython (in the IP runtime)?

Ans: Yes!

Question So, I should be able to use my C# classes in a multiple inheritance scenario from IronPython?

Ans: Yes!

Making it all work

If you create a class in managed C# you are free to pass it along for use to the IronPython runtime and thus access it using IronPython. Let’s take the following class created in C#:

public class Person
{
    public string Name;
}

Using my IronPython WPF interactive console control, I can interactively create new classes with IronPython and use my C# Person class as the base class in an inheritance object graph. Here’s the code as typed at the interpreter:

multi_inheritance_using_csh

As you can see, first up I imported the relevant namespace (module) where the C# Person class is defined. The first class derived from Person is Employee and then I have derived WarehouseManager from Employee which leaves our Inheritance tree like this:

  • Person
    • Employee
      • WarehouseManager

You can also see that both the derived classes have access to the Name property of the C# Person class which proves that the Person class has been included in the inheritance of the Employee and subsequently WarehouseManager classes.

So that’s some plain old inheritance using C# classes. Now lets take a quick look at multiple inheritance using the same C# class.

mutliple_inheritance_tipas

When should I use this feature?

Probably never according to some people, yet for every objector there seems to be fan. Languages that do support multiple inheritance, often come with a disclaimer for programmers to avoid their usage and Python would appear to be no exception in this case. The above is a good example of why multiple inheritance isn’t necessarily a good thing, given that a manager is presumably an employee and at the very least a person. Nonetheless it demonstrates the intent and this post isn’t so much about the ‘why’ but mostly for now it’s about the how. I will follow up soon with more about the ‘why’ and ‘when’ in a subsequent post.

Carefully managed, I can see it’s potential uses could be enticing. Yes, yes I know “composition over inheritance” etc…There is never one shoe fits all!

Just in case you where wondering

If you were thinking of doing something like this in C#:

public class WidgetA
{
    //….etc
}

public class WidgetB
{
    //….etc
}

Followed up by:

widgetA-B-C_ironpython

You will see that we cant in fact use two classes created in a CLI compliant language. This will effectively stop crazy stuff like this:

class MutantUi(Form, Button):
    def SetTitles(self):
        self.Text = What happens here

But I am completely free to do this:

from Org.TechA.Wpf.ControlsHarness import *

class PythonMixin(object):
    def method(self):
        print method

class Mutant(PythonMixin, Person):
    def MutantMethod(self):
        print mutant method

 m = Mutant()
 m.method()
 m.Name = Simon
 print m.Name
 m.MutantMethod()
 

So there you have it, Multiple inheritance / mixins with C# (well kinda)!

Share/Save/Bookmark

2 comments

Type Member Name Resolution with Functions – Part 2.0

Adding to the previous post, the PropertyNameResolver class needs to expand it’s horizons and resolve method names and field names. Given the expanded requirement we probably need to refactor the name of the class to something more appropriate. Here is a more fleshed out idea of what it might look like:

public class MemberNameResolver<T>
{
    public static string ResolveProperty<TPropertyType>
        (Expression<Func<T, TPropertyType>> expression)
    {
        Func<Expression<Func<T, TPropertyType>>, string>
            prop_name_function = l =>
        {
            return GetNameFromExpression(l.Body);
        };
        var property_name =
            typeof(T).GetProperty(prop_name_function(expression)).Name;
        return property_name;
    }

    public static string ResolveMethod(Expression<Action<T>> expression)
    {
        Func<Expression<Action<T>>, string>
            prop_name_function = l =>
            {
                return GetNameFromExpression(l.Body);
            };
        var property_name =
            typeof(T).GetMethod(prop_name_function(expression)).Name;
        return property_name;
    }

    public static string ResolveField<TPropertyType>
        (Expression<Func<T, TPropertyType>> expression)
    {
        Func<Expression<Func<T, TPropertyType>>, string>
            prop_name_function = l =>
            {
                return GetNameFromExpression(l.Body);
            };
        var property_name =
            typeof(T).GetField(prop_name_function(expression)).Name;
        return property_name;
    }

    private static string GetNameFromExpression(Expression body)
    {
        if (ExpressionType.MemberAccess == body.NodeType)
        {
            var memberExpr = (MemberExpression)body;
            return memberExpr.Member.Name;
        }
        else if (ExpressionType.Call == body.NodeType)
        {
            var methodExpr = (MethodCallExpression)body;
            return methodExpr.Method.Name;
        }
        else
        {
            throw new NotImplementedException(
                string.Format(“Resolving names from expression types “ +
                “of {0} is not implemented!”,
                body.Type.Name));
        }
    }
}
Previously we did not account for method calls and as one kind soul articulately pointed out, the string manipulation was somewhat awkward. Mark pointed out Damien’s neat solution by way of digging into the expression body.

Notice the newly specialized Resolve methods now allow a usage like the following:

var member1 =
    MemberNameResolver<Criteria>
    .ResolveProperty<int>(c => c.PageCounter);
var member2 =
    MemberNameResolver<Criteria>
    .ResolveMethod(c => c.SomeMethod());
var member3 =
    MemberNameResolver<Criteria>
    .ResolveField(c => c.Percent);
var member4 =
    MemberNameResolver<Criteria>
    .ResolveMethod(c => c.SomeMethodWithArgs(default(string),
        default(int), default(string[])));

Console.WriteLine(member1);
Console.WriteLine(member2);
Console.WriteLine(member3);
Console.WriteLine(member4);

Producing the following output:

console_functions_memer_resolve1

Getting more out of Functions

So far the approach is a little static from a functional point of view so perhaps we could do this a little differently? If we define the following functions we get some equivalent behaviour to our utility class.

Func<Expression<Func<Criteria, int>>, Expression> criteriaFunction =
    c => c.Body;

Func<Expression, string> propertyResolverFunction = e =>
{
    if (ExpressionType.MemberAccess == e.NodeType)
    {
        var memberExpr = (MemberExpression)e;
        return memberExpr.Member.Name;
    }
    else if (ExpressionType.Call == e.NodeType)
    {
        var methodExpr = (MethodCallExpression)e;
        return methodExpr.Method.Name;
    }
    else
    {
        throw new NotImplementedException(
            string.Format(“Resolving names from expression types “ +
            “of {0} is not implemented!”,
            e.Type.Name));
    }
};

var propertyName =
    propertyResolverFunction(
        criteriaFunction(c => c.PageCounter));

Console.WriteLine(propertyName);

Here we have created two functions that can be used together to achieve our required end result. The first function criteriaFunction, takes a generic expression as an argument and returns an expression. The second function propertyResolverFunction, takes an expression as it’s argument and returns a string. By passing one function as an argument to the other, we achieve the same results as with the static utility class already demonstrated. To collapse this even further we can wrap up both those functions  into one.

Func<Expression<Func<Criteria, string>>, Func<Expression, string>> allInOne =
    c => e =>
    {

        if (ExpressionType.MemberAccess == e.NodeType)
        {
            var memberExpr = (MemberExpression)e;
            return memberExpr.Member.Name;
        }
        else if (ExpressionType.Call == e.NodeType)
        {
            var methodExpr = (MethodCallExpression)e;
            return methodExpr.Method.Name;
        }
        else
        {
            throw new NotImplementedException(
                string.Format(“Resolving names from expression types “ +
            “of {0} is not implemented!”,
                e.Type.Name));
        }
    };

Expression<Func<Criteria, string>> exp = c => c.Levels;
var property_name_allinone = allInOne(exp)(exp.Body);

Console.WriteLine(property_name_allinone);

When we call the allinone function with the expression argument, it returns a function that in turns take the body property of the same expression that was passed to the higher order function. All the code in the post presumes the the following class:

public class Criteria
{
    public decimal Percent;

    private int _pageCounter;

    public int PageCounter
    {
        get { return _pageCounter; }
        set { _pageCounter = value; }
    }

    private string _levels;

    public string Levels
    {
        get { return _levels; }
        set { _levels = value; }
    }

    public void SomeMethod() { }

    public void SomeMethodWithArgs(string arg1, int arg2,
        params string[] arg3) { }
}

Share/Save/Bookmark

1 comment

Functional Type member resolution with C#

An interesting problem cropped up today regarding reflection and how LINQ might make for a strongly typed solution. K. Scott Allen suggested a while back to use lambdas to remove the use of ‘magic’ strings in building Fetching Intentions used in NFetchSpec and it was suggested by my colleague Mark that a similar approach be used in resolving a types property name using strongly typed expressions. Given the following class:

public class Criteria
{
    private int _pageCounter;

    public int PageCounter
    {
        get { return _pageCounter; }
        set { _pageCounter = value; }
    }

    private string _levels;

    public string Levels
    {
        get { return _levels; }
        set { _levels = value; }
    }
}

I want to dynamically resolve any property name using an Expression such as:

Expression<Func<Criteria, string>> f = c => c.Levels;

After fumbling around for a while it occurred that functional programming was yet again the simplest way to approach this.

public class PropertyNameResolver<T>
{
    public static string Resolve<TPropertyType>
        (Expression<Func<T, TPropertyType>> expression)
    {
        Func<Expression<Func<T, TPropertyType>>, string>
            prop_name_function = l =>
            {
                int posDot = l.Body.ToString().LastIndexOf(“.”) + 1;
                return l.Body.ToString().Remove(0, posDot);
            };
        var property_name =
            typeof(T).GetProperty(prop_name_function(expression)).Name;
        return property_name;
    }
}

By supplying the expression and encapsulating the function that takes the expression as an argument, we get access to the body and parameters in the expression tree built by the original lambda and when be execute the outer function we can extrapolate the property name. Here’s an example of the usage:

var pc = PropertyNameResolver<Criteria>.Resolve<int>(c => c.PageCounter);
Console.WriteLine(pc);

Functional goodness in C#.

Share/Save/Bookmark

4 comments

Next Page »

Creative Commons Attribution-ShareAlike 2.5 Australia
Creative Commons Attribution-ShareAlike 2.5 Australia