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.

Resolving patch:
diff --git a/janitor/functions.py b/janitor/functions.py
--- a/janitor/functions.py
+++ b/janitor/functions.py
@@ -631,7 +631,7 @@ def fill_empty(df, columns, value):
 
 
 @pf.register_dataframe_method
-def expand_column(df, column, sep, concat=True):
+def expand_column(df, sep, column_name=None, concat=True, **kwargs):
     """
     Expand a categorical column with multiple labels into dummy-coded columns.
 
@@ -641,7 +641,8 @@ def expand_column(df, column, sep, concat=True):
 
     .. code-block:: python
 
-        df = expand_column(df, column='col_name',
+        df = expand_column(df,
+                           column_name='col_name',
                            sep=', ')  # note space in sep
 
     Method chaining example:
@@ -650,21 +651,28 @@ def expand_column(df, column, sep, concat=True):
 
         import pandas as pd
         import janitor
-        df = pd.DataFrame(...).expand_column(df, column='col_name', sep=', ')
+        df = pd.DataFrame(...).expand_column(df,
+                                             column_name='col_name',
+                                             sep=', ')
 
     :param df: A pandas DataFrame.
-    :param column: A `str` indicating which column to expand.
+    :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`).
     """
-    expanded = df[column].str.get_dummies(sep=sep)
+    if kwargs and column_name is not None:
+        raise TypeError("Mixed usage of column and column_name")
+    if column_name is None:
+        warnings.warn("column is deprecated. You should use column_name.")
+        column_name = kwargs["column"]
+    expanded_df = df[column_name].str.get_dummies(sep=sep)
     if concat:
-        df = df.join(expanded)
+        df = df.join(expanded_df)
         return df
     else:
-        return expanded
+        return expanded_df
 
 
 @pf.register_dataframe_method


Test patch:
diff --git a/tests/functions/test_expand_column.py b/tests/functions/test_expand_column.py
--- a/tests/functions/test_expand_column.py
+++ b/tests/functions/test_expand_column.py
@@ -10,8 +10,8 @@ def test_expand_column():
     }
 
     df = pd.DataFrame(data)
-    expanded = df.expand_column("col1", sep=", ", concat=False)
-    assert expanded.shape[1] == 6
+    expanded_df = df.expand_column(column_name="col1", sep=", ", concat=False)
+    assert expanded_df.shape[1] == 6
 
 
 @pytest.mark.functions
@@ -21,5 +21,7 @@ def test_expand_and_concat():
         "col2": [1, 2, 3, 4],
     }
 
-    df = pd.DataFrame(data).expand_column("col1", sep=", ", concat=True)
+    df = pd.DataFrame(data).expand_column(
+        column_name="col1", sep=", ", concat=True
+    )
     assert df.shape[1] == 8