SercioSoydanov
SercioSoydanov

Reputation: 1410

How to properly implement method cascading - chaining in Python?

I have a python code roughly like this:

class SomeClass():

    def get_date(self):
        date = # read the data from the database in YYYY-MM-DD HH:MM:SS format
        return date

now, I will use the returned value in an API query, which accepts the input as a unix timestamp. Actually I can give the returned date to another function to have it converted to a timestamp, but I thought it would be a good opportunity to learn about function cascading / chaining, which I've always wondered about in Python.

Now, what I basically want to achieve is something like this:

I've looked into some examples of function cascading. They are mostly saying that key to this is returning the self, but I could not find any info about how to implement it in the way I need to.

I basically need the return value to be fed into the second function (I guess), but not sure if it is possible, and don't know how to do it. Any ideas?

Upvotes: 3

Views: 1354

Answers (1)

Logan Bertram
Logan Bertram

Reputation: 1942

What you're looking for looks more like this:

import time
import calendar

class DateClass():

  def get_date(self):
    self = # read the data from the database in YYYY-MM-DD HH:MM:SS format
    return self

  def as_timestamp(self):
    mysql_time = time.strptime(self, '%Y-%m-%d %H:%M:%S')
    self = calendar.timegm(mysql_time)
    return self

d = DateClass()
print(d.get_date())
print(d.get_date().as_timestamp())
print(d)
d.get_date()
print(d)

The first output would be the MySQL datetime, and the second would be the Unix timestamp, the third would also be the unix timestamp and the fourth would be the datetime. get_date() and as_timestamp() mutate the instance d when called on it.

In this configuration, as_timestamp() requires get_date(), which seems to be in line with your question, but you could change that by assigning self from the database in as_timestamp() like this:

def as_timestamp(self):
  self = # read the data from the database in YYYY-MM-DD HH:MM:SS format
  mysql_time = time.strptime(self, '%Y-%m-%d %H:%M:%S')
  self = calendar.timegm(mysql_time)
  return self

which will make it possible to call as_timestamp() independent of get_date(). You can also then add d.as_timestamp() to mutate any iteration of d so that d is a timestamp.

Upvotes: 2

Related Questions