Managed Attributes in Python

In a previous post, I detailed how to maintain encapsulation using Python’s property. In this piece, I go through how/why to manage and apply validation to class attributes in an object-oriented fashion by means of a fairly plausible example.

A type is the parent class of class, therefore any class is actually a sub-type of type. The following are equivalent:

a = int(8)
a = 8
type(a) # python knows to create an int without being explicit
    int

The point of implementing custom attribute types is (in my case), for validation. The general pattern for creating a class that serves as a type to validate instance attributes is as follows (for a descriptor):

[Read more]

Encapsulation with Python Properties

If you ever created a class in Python, you probably accessed it using dot notation (i.e. instance_name.attribute_name).

That’s python’s way of calling getattr by means of an alias:

class A:
    var = 10
    pass

a = A()
# this is how Python accesses attributes
getattr(a, 'var')
10
a.__getattribute__('var') # above is an alias for this
10

The most “pythonic” way of getting and setting attributes is using dot notation:

A.var = 11
print(A.var)
11

which is short for the dunder getattribute method

[Read more]

Using Decorators to Solve Date Problems

A decorator is the gateway drug into the world of Python metaprogramming. In python, everything, everything, is an object (specifically a dictionary but let’s not go there). That means that we can pass in and return any object regardless of its types, especially regardless of its type.

If I define a function:

def fn(*args, **kwargs):
    pass

and now call type on fn

type(fn)
function

the type is function (No surprises there). But remember, we can return anything. So if I really wanted to, I could do the following:

[Read more]

Mapping Pandas Columns

A few weeks ago I had to figure out how to perform a mapping of pandas column values to other values. This was not necessarily a discrete mapping, as in the initial column value needed to match a range.

The dataframe I was working with resembled the following:

   value
0     88
1      3
2      5
3     65
4     72
5     54

And there were a set of conditions by which I needed to replace. Think of it like this, if the above were a group of marks for an exam, I would want to map it based on the value ranges.

[Read more]

Zero-Padding a CSV with AWK

This was purely out of sheer need, and this was the fastest way I could’ve gotten it done (I ended up learning a LOT about CLI and the awk command from this, so I’m really grateful for that)

The problem: I have a column in a utf-8 CSV file of type Integer, which should actually be type string and zero-padded up to (let’s say length N).

~/projects/awk_pad ❯ cat out.csv             
a,Y,1
b,N,10
c,Y,12223253

What I want, is the following (output from the cat tool):

[Read more]