Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import Python methods of existing classes selectively?

Tags:

python

pandas

Consider the following example that imports additional Pandas methods from the pyjanitor package.

import pandas as pd
import janitor

df = pd.DataFrame({
    'Column One': [1, 2, 3],
    'Column-Two': [4, 5, 6],
    'Column@Three': [7, 8, 9],
})

df_cleaned = df.clean_names()
print(df_cleaned)
#>    column_one  column_two  column@three
#> 0           1           4             7
#> 1           2           5             8
#> 2           3           6             9

Is there a way to import methods from Python packages, modules, or other sources more transparently/explicitly (to know which method came from which package) and/or selectively (to import only the methods of interest, e.g., only .clean_names() but not the remaining ones)?

Note: I do not want to import a method as a function and use it as a function. I would like to control what methods are imported.

like image 753
GegznaV Avatar asked Mar 11 '26 04:03

GegznaV


1 Answers

pyjanitor is extremely unusual. Adding methods to a class defined somewhere else is technically legal in Python, but almost no one does it. Most of the time, you can safely assume that any methods of a class come from the module that defines the class, or are inherited from parent classes.

It is not possible to selectively import only some of an object's methods. An object has the same methods no matter what code is looking at it. (It might suddenly grow more methods if a module like pyjanitor adds more, but if so, those new methods will be available to any code that accesses the object after that point.)

like image 195
user2357112 supports Monica Avatar answered Mar 13 '26 17:03

user2357112 supports Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!