Repository: pyjanitor-devs/pyjanitor

Issue:
[ENH] Naming conventions
I wanted to discuss naming conventions for the various functions and arguments for consistency. `expand_column` has a parameter `column` whereas `add_column` had `col_name`.

Also, is `_column` necessary in each function? Would it be ok to just have an `add()` or `transform()` method? In general I'm more on the side of more verbose function names, but just wanted to throw the idea out there.

Similarly, when following the format of `limit_column_characters` functions like `change_type` should probably be named `change_column_type`.

I'm not married to any of this (except the function arguments, those should be consistent) but wanted to get peoples' ideas.


Discussion:
Thanks for raising this issue, @szuckerman! I’m also in favor of consistent naming schemes. 

Breaking this down a bit:

### Columns

I vote in favor of “col_name”. It is more explicit than “column”.

### Verbose vs Concise Functions

Zen of Python states that explicit is better than implicit, with no qualifiers afterwards. For that reason, I vote in favor of verbose names. 
Labelling this a "good first issue" for newcomers, as it basically involves a find-and-replace.
I'd be interested in taking on this issue if no one has done so yet. Would this need some support to warn users that names have changed, and that previous names will no longer work in a future version?
@HectorM14 yes, that would be great! Please do go ahead.

> Would this need some support to warn users that names have changed, and that previous names will no longer work in a future version?

Yes agreed. Since we're at version 0.16.x right now, the responsible way to evolve the API is to keep it through the next two minor versions, and the deprecate it at the next major or 3rd minor version. Perhaps raising a warning if and only if certain functions are called/keyword arguments are used.

Personally, I would prefer one function at a time, which makes it easier to review, but at the same time, I think we should trust your judgment - especially if there's things that are logically groupable, feel free to PR in them together. Looking forward to what you've got; also, don't hesitate to ping in here!
Great, I'll use my best judgement for PR scope. Is there a standard way to deprecate/discourage old argument names? I was thinking of using decorators to keep the method APIs clear about their usage going forward.
Thanks @HectorM14!

> Is there a standard way to deprecate/discourage old argument names? 

To the best of my knowledge, the standard way to do this should be to insert a conditional checking to see if that old argument name was called or not, and then inside the conditional:

1. Raise a warning.
2. Assign the value of the old argument to a new variable that has the same name as the new argument.

For example:

```python
from warning import warning

def deprecation_warning(old_arg, new_arg):
    """generic warning function."""
    warning(f"{argname.__name__} is deprecated, and will be replaced with {new_arg.__name__}")

def func(df, old_arg1, arg2, arg3, new_arg):
    """docstring here"""
    if old_arg1 is not None:
        deprecation_warning(old_arg1, new_arg)
        new_arg = old_arg1
    # continue code
```

> I was thinking of using decorators to keep the method APIs clear about their usage going forward.

That might actually be better than what I had up there! I'd like to see the pattern in the first PR, it'd be educational for myself.
[Relevant PyCon talk on refactoring and adding `warnings` for legacy code](https://youtu.be/D_6ybDcU5gc?t=787). The actual code for warnings comes in around 17:00.
Oh cool, thanks for sharing that, @szuckerman! 
Following advice in that talk, we could update `expand_column()` as follows:

```python
def expand_column(df, sep, column_name=None, concat=True, **kwargs):
    """
    Expand a categorical column with multiple labels into dummy-coded columns.

    Super sugary syntax that wraps :py:meth:`pandas.Series.str.get_dummies`.

    Functional usage example:

    .. code-block:: python

        df = expand_column(df, column_name='col_name',
                           sep=', ')  # note space in sep

    Method chaining example:

    .. code-block:: python

        import pandas as pd
        import janitor
        df = pd.DataFrame(...).expand_column(df, column_name='col_name', sep=', ')

    :param df: A pandas DataFrame.
    :param column_name: A `str` indicating which column to expand.
    :param sep: The delimiter. Example delimiters include `|`, `, `, `,` etc.
    :param bool concat: Whether to return the expanded column concatenated to
        the original dataframe (`concat=True`), or to return it standalone
        (`concat=False`).
    """
    if kwargs and column_name is not None:
        raise TypeError('Mixed usage of column and column_name')
    if column_name is None:
        warnings.warn('Use of column is deprecated. You should use column_name.')
        column_name = kwargs['column']
    expanded = df[column_name].str.get_dummies(sep=sep)
    if concat:
        df = df.join(expanded)
        return df
    else:
        return expanded
```
One notable consequence of this, is having to set column_name as None, which requires us to move its position in the list of arguments (during the deprecation period). 

The way it's written also assumes that additional arguments received would only relate to deprecated usage, and include `column`.

Another issue is to decide what is the proper variable form of "column". Even when the variable names are explicit, `*_col_*` and `*_column_*` are both used throughout the code.
@HectorM14 those are great points you've raised :smile:. 

> Another issue is to decide what is the proper variable form of "column". Even when the variable names are explicit, `*_col_*` and `*_column_*` are both used throughout the code.

I am guilty of being inconsistent here, as I sometimes use `col` and sometimes use `column` and sometimes use `colname`. Yes, being consistent is a great thing. I would personally vote for `column_name`, in adherence to "explicit is better than implicit", but if there are better reasons (brevity, perhaps?) for other conventions, not a problem! I have no strong opinions on this one, as long as we can make it towards consistency in the end!
I like column_name too. I can aim for being explicit with these names unless they become too unwieldy. I'll start making individual PRs for each updated function. Updating variables relating columns is easy, but if anyone finds other variables that should be updated, they can list them here.
Updating names is becoming a bit more complicated. For example we currently have:
```python
def coalesce(df, columns, new_column_name):
```
Following the current style we've been using, we would update this to:
```python
def coalesce(df, new_column_name, columns=None, **kwargs):
```
But quick, intuitive usage of this function from `example.py` is:
```python
df = (
    df
    .coalesce(["certification", "certification_1"], "certification")
```
With the proposed changes, this would become (due to rearranging of argument order):
```python
df = (
    df
    .coalesce(column_names=["certification", "certification_1"], new_column_name="certification")
)
```
Which is excessively more complicated. So our fix will have to be more complex/clever to keep it clean for the user.
@HectorM14 I wouldn't worry too much about the kwargs. In Python, explicit is better than implicit, generally speaking. I find myself writing out kwarg names even though it is sometimes easier to not do so, because I recognize that it makes the code more readable, actually. I would encourage you to keep going with the PRs :smile:. 
Thanks @ericmjl , explicit is good!
I actually came across this example on [SO](https://stackoverflow.com/questions/49802412/how-to-implement-deprecation-in-python-with-argument-alias):

```python
import functools
import warnings

def _deprecated_alias(**aliases):
    def deco(f):
        @functools.wraps(f)
        def wrapper(*args, **kwargs):
            _rename_kwargs(f.__name__, kwargs, aliases)
            return f(*args, **kwargs)
        return wrapper
    return deco

def _rename_kwargs(func_name, kwargs, aliases):
    for alias, new in aliases.items():
        if alias in kwargs:
            if new in kwargs:
                raise TypeError('{} received both {} and {}'.format(
                    func_name, alias, new))
            warnings.warn('{} is deprecated; use {}'.format(alias, new),
                          DeprecationWarning)
            kwargs[new] = kwargs.pop(alias)
```
using this as a decorator we would be able to do:
```python
@_deprecated_alias(a='alpha', b='beta')
def simple_sum(alpha, beta):
    return alpha + beta

print(simple_sum(alpha=6, beta=9))
print(simple_sum(a=6, b=9))
```
With this method, updating the argument names would be much faster, and when the deprecation period has expired, we only need to delete one/two lines instead of 6+ lines currently. If we used this approach, I would make the above functions more human-readable.

What do you think?
This is a really great find! I'm all for reducing the maintenance burden :smile:. 

Perhaps this function can be inserted into `utils.py`? Be sure to acknowledge the source by linking to SO!

Also, does this mean you'd redo the name changes already PR'd? I don't want to put too much pressure on you, but if you'd do so, that'd be superb for maintenance purposes!
Cool! `utils.py` sounds like a good place. 

I'll link to the SO post in the `_deprecated_alias` docstring. 
I'll start with a PR that includes these new functions, and include some tests to make sure it works/fails/warns as expected. After that, I'm fine updating the previously changed functions and moving forward. I actually was considering revisiting those functions anyway after learning that there was an actual `DeprecationWarning` subclass.
I have been merging from `upstream` before committing, should I be rebasing instead?
Rebasing works as well! It's a suggestion from @zbarry, which, frankly speaking, I rarely do, because it's just easier to remember `git fetch upstream; git merge upstream/dev`. :smile:

That said, good practices are good to use, so I'm going to try moving to rebasing now.

Resolving patch:
diff --git a/janitor/functions.py b/janitor/functions.py
--- a/janitor/functions.py
+++ b/janitor/functions.py
@@ -1700,15 +1700,19 @@ def row_to_names(
 
 
 @pf.register_dataframe_method
+@deprecated_alias(col_name="column_name")
 def round_to_fraction(
-    df, col_name: str = None, denominator: float = None, digits: float = np.inf
+    df,
+    column_name: str = None,
+    denominator: float = None,
+    digits: float = np.inf,
 ):
     """
     Round all values in a column to a fraction.
 
     Also, optionally round to a specified number of digits.
-
-    :param number: The number to round
+    :param df: A pandas dataframe.
+    :param column_name: Name of column to round to fraction.
     :param denominator: The denominator of the fraction for rounding
     :param digits: The number of digits for rounding after rounding to the
         fraction. Default is np.inf (i.e. no subsequent rounding)
@@ -1799,7 +1803,7 @@ def round_to_fraction(
 
     """
 
-    check("col_name", col_name, [str])
+    check("column_name", column_name, [str])
 
     if denominator:
         check("denominator", denominator, [float, int])
@@ -1817,13 +1821,16 @@ def _round_to_fraction(number, denominator, digits=np.inf):
         _round_to_fraction, denominator=denominator, digits=digits
     )
 
-    df[col_name] = df[col_name].apply(_round_to_fraction_partial)
+    df[column_name] = df[column_name].apply(_round_to_fraction_partial)
 
     return df
 
 
 @pf.register_dataframe_method
-def transform_column(df, col_name: str, function, dest_col_name: str = None):
+@deprecated_alias(col_name="column_name", dest_col_name="dest_column_name")
+def transform_column(
+    df, column_name: str, function, dest_column_name: str = None
+):
     """
     Transforms the given column in-place using the provided function.
 
@@ -1834,7 +1841,7 @@ def transform_column(df, col_name: str, function, dest_col_name: str = None):
     .. code-block:: python
 
         # YOU NO LONGER NEED TO WRITE THIS!
-        df[col_name] = df[col_name].apply(function)
+        df[column_name] = df[column_name].apply(function)
 
     With the method chaining syntax, we can do the following instead:
 
@@ -1842,7 +1849,7 @@ def transform_column(df, col_name: str, function, dest_col_name: str = None):
 
         df = (
             pd.DataFrame(...)
-            .transform_column(col_name, function)
+            .transform_column(column_name, function)
         )
 
     With the functional syntax:
@@ -1850,30 +1857,31 @@ def transform_column(df, col_name: str, function, dest_col_name: str = None):
     .. code-block:: python
 
         df = pd.DataFrame(...)
-        df = transform_column(df, col_name, function)
+        df = transform_column(df, column_name, function)
 
     :param df: A pandas DataFrame.
-    :param col_name: The column to transform.
+    :param column_name: The column to transform.
     :param function: A function to apply on the column.
-    :param dest_col_name: The column name to store the transformation result
+    :param dest_column_name: The column name to store the transformation result
         in. By default, replaces contents of original column.
     :returns: A pandas DataFrame with a transformed column.
     """
 
-    if dest_col_name is None:
-        dest_col_name = col_name
+    if dest_column_name is None:
+        dest_column_name = column_name
 
-    df[dest_col_name] = df[col_name].apply(function)
+    df[dest_column_name] = df[column_name].apply(function)
     return df
 
 
 @pf.register_dataframe_method
+@deprecated_alias(columns="column_names", new_names="new_column_names")
 def transform_columns(
     df,
-    columns: List[str],
+    column_names: List[str],
     function,
     suffix: str = None,
-    new_names: Dict[str, str] = None,
+    new_column_names: Dict[str, str] = None,
 ):
     """
     Super syntactic sugar to transform a list of columns by the same
@@ -1919,7 +1927,7 @@ def transform_columns(
             .transform_column(
                 ['col1', 'col2', 'col3'],
                 np.log10,
-                new_names={
+                new_column_names={
                     'col1': 'transform1',
                     'col2': 'transform2',
                     'col3': 'transform3',
@@ -1928,33 +1936,35 @@ def transform_columns(
         )
 
     :param df: A pandas DataFrame.
-    :param columns: An iterable of columns to transform.
+    :param column_names: An iterable of columns to transform.
     :param function: A function to apply on each column.
     :param suffix: (optional) Suffix to use when creating new columns to hold
         the transformed values.
-    :param new_names: (optional) An explicit mapping of old column names to
-        new column names.
+    :param new_column_names: (optional) An explicit mapping of old column names
+        to new column names.
     :returns: A pandas DataFrame with transformed columns.
     """
-    dest_col_names = dict(zip(columns, columns))
+    dest_column_names = dict(zip(column_names, column_names))
 
-    check("columns", columns, [list, tuple])
+    check("column_names", column_names, [list, tuple])
 
-    if suffix is not None and new_names is not None:
-        raise ValueError("only one of suffix or new_names should be specified")
+    if suffix is not None and new_column_names is not None:
+        raise ValueError(
+            "only one of suffix or new_column_names should be specified"
+        )
 
     if suffix:  # If suffix is specified...
         check("suffix", suffix, [str])
-        for col in columns:
-            dest_col_names[col] = col + suffix
+        for col in column_names:
+            dest_column_names[col] = col + suffix
 
-    if new_names:  # If new_names is specified...
-        check("new_names", new_names, [dict])
-        dest_col_names = new_names
+    if new_column_names:  # If new_column_names is specified...
+        check("new_column_names", new_column_names, [dict])
+        dest_column_names = new_column_names
 
     # Now, transform columns.
-    for oldcol, newcol in dest_col_names.items():
-        df = transform_column(df, oldcol, function, newcol)
+    for old_col, new_col in dest_column_names.items():
+        df = transform_column(df, old_col, function, new_col)
 
     return df
 
@@ -2270,10 +2280,11 @@ def _replace_original_empty_string_with_none(x):
 
 
 @pf.register_dataframe_method
+@deprecated_alias(col_name="column_name", type="cleaning_style")
 def currency_column_to_numeric(
     df,
-    col_name: str,
-    type: str = None,
+    column_name: str,
+    cleaning_style: str = None,
     cast_non_numeric: dict = None,
     fill_all_non_numeric: float = None,
     remove_non_numeric: bool = False,
@@ -2285,9 +2296,9 @@ def currency_column_to_numeric(
     Empty strings (i.e. `''`) are retained as `NaN` values.
 
     :param df: The DataFrame
-    :param col_name: The column to modify
-    :param type: What type of cleaning to perform. If None, standard cleaning
-        is applied. Options are: 'accounting'.
+    :param column_name: The column to modify
+    :param cleaning_style: What style of cleaning to perform. If None, standard
+        cleaning is applied. Options are: 'accounting'.
     :param cast_non_numeric: A dict of how to coerce certain strings. For
         example, if there are values of 'REORDER' in the DataFrame,
         {'REORDER': 0} will cast all instances of 'REORDER' to 0.
@@ -2295,7 +2306,7 @@ def currency_column_to_numeric(
         strings to the same value. For example,  fill_all_non_numeric=1, will
         make everything that doesn't coerce to a currency 1.
     :param remove_non_numeric: Will remove rows of a DataFrame that contain
-        non-numeric values in the `col_name` column. Defaults to `False`.
+        non-numeric values in the `column_name` column. Defaults to `False`.
     :returns: A mutated DataFrame.
 
     :Example Setup:
@@ -2449,11 +2460,13 @@ def currency_column_to_numeric(
         7   NaN     2.456234                   2      leopard   Shanghai
         """
 
-    check("col_name", col_name, [str])
+    check("column_name", column_name, [str])
 
-    column_series = df[col_name]
-    if type == "accounting":
-        df.loc[:, col_name] = df[col_name].apply(_clean_accounting_column)
+    column_series = df[column_name]
+    if cleaning_style == "accounting":
+        df.loc[:, column_name] = df[column_name].apply(
+            _clean_accounting_column
+        )
         return df
 
     if cast_non_numeric:
@@ -2481,13 +2494,16 @@ def currency_column_to_numeric(
         _replace_original_empty_string_with_none
     )
 
-    df = df.assign(**{col_name: pd.to_numeric(column_series)})
+    df = df.assign(**{column_name: pd.to_numeric(column_series)})
 
     return df
 
 
 @pf.register_dataframe_method
-def select_columns(df: pd.DataFrame, search_cols: List, invert: bool = False):
+@deprecated_alias(search_cols="search_column_names")
+def select_columns(
+    df: pd.DataFrame, search_column_names: List, invert: bool = False
+):
     """
     Method-chainable selection of columns.
 
@@ -2500,8 +2516,8 @@ def select_columns(df: pd.DataFrame, search_cols: List, invert: bool = False):
         df = pd.DataFrame(...).select_columns(['a', 'b', 'col_*'], invert=True)
 
     :param df: A pandas DataFrame.
-    :param search_cols: A list of column names or search strings to be used\
-        to select. Valid inputs include:
+    :param search_column_names: A list of column names or search strings to be
+        used to select. Valid inputs include:
         1) an exact column name to look for
         2) a shell-style glob string (e.g., `*_thing_*`)
     :param invert: Whether or not to invert the selection.
@@ -2512,7 +2528,7 @@ def select_columns(df: pd.DataFrame, search_cols: List, invert: bool = False):
 
     full_column_list = []
 
-    for col in search_cols:
+    for col in search_column_names:
         search_string = translate(col)
         columns = [col for col in df if re.match(search_string, col)]
         full_column_list.extend(columns)


Test patch:
diff --git a/tests/functions/test_select_columns.py b/tests/functions/test_select_columns.py
--- a/tests/functions/test_select_columns.py
+++ b/tests/functions/test_select_columns.py
@@ -12,7 +12,7 @@
 )
 def test_select_columns(dataframe, invert, expected):
     columns = ["a", "Bell__Chart", "cities"]
-    df = dataframe.select_columns(search_cols=columns, invert=invert)
+    df = dataframe.select_columns(search_column_names=columns, invert=invert)
 
     pd.testing.assert_frame_equal(df, dataframe[expected])
 
@@ -27,6 +27,6 @@ def test_select_columns(dataframe, invert, expected):
 )
 def test_select_columns_glob_inputs(dataframe, invert, expected):
     columns = ["Bell__Chart", "a*"]
-    df = dataframe.select_columns(search_cols=columns, invert=invert)
+    df = dataframe.select_columns(search_column_names=columns, invert=invert)
 
     pd.testing.assert_frame_equal(df, dataframe[expected])
diff --git a/tests/functions/test_transform_column.py b/tests/functions/test_transform_column.py
--- a/tests/functions/test_transform_column.py
+++ b/tests/functions/test_transform_column.py
@@ -20,7 +20,7 @@ def test_transform_column_with_dest(dataframe):
     expected_df = dataframe.assign(a_log10=np.log10(dataframe["a"]))
 
     df = dataframe.copy().transform_column(
-        "a", np.log10, dest_col_name="a_log10"
+        "a", np.log10, dest_column_name="a_log10"
     )
 
     pd.testing.assert_frame_equal(df, expected_df)
diff --git a/tests/functions/test_transform_columns.py b/tests/functions/test_transform_columns.py
--- a/tests/functions/test_transform_columns.py
+++ b/tests/functions/test_transform_columns.py
@@ -43,7 +43,7 @@ def test_transform_column_with_new_names(dataframe):
         .transform_columns(
             ["another", "column"],
             np.log10,
-            new_names={"another": "hello", "column": "world"},
+            new_column_names={"another": "hello", "column": "world"},
         )
     )
 
@@ -62,7 +62,7 @@ def test_suffix_newname_validation(dataframe):
             .transform_columns(
                 ["another", "column"],
                 np.log10,
-                new_names={"another": "hello", "column": "world"},
+                new_column_names={"another": "hello", "column": "world"},
                 suffix="_log",
             )
         )