Python static class or functions in modules [duplicate] - python

This question already has answers here:
python - should I use static methods or top-level functions
(5 answers)
Closed 6 years ago.
I need something to organize some utilty functions.
Variant 1.
create module and write all functions in this module.
Variant 2.
(since python has no staticclass)
create class with only static methods in main module
In general, there is no big difference.Like :
var 1)
import functionsmodule
workers = functionmodule.get_all_workers(**kwargs)
var 2)
workers = FunctionClass.get_all_workers(**kwargs)
I like the second one though.
Questions is : what is best way to do such organization ?

You could also do:
from functionsmodule import get_all_workers, some_other_method
workers = get_all_workers(**kwargs)
After a couple of months learning python, this is my preferred solution. It cleans up the code without the need to reference a class or module. I'd only recommend this if your utilities method names WONT clash with builtins or other functions
I'd usually organise these re-usable/utilities within a common package and implement something like:
from common.functions import get_all_workers, some_other_method
workers = get_all_workers(**kwargs)
EDIT: Based on your "get_all_workers" method name - I'd imagine this should go into some sort of persistence/worker class rather than a general utilities class

Related

different python files sharing the same variables [duplicate]

This question already has answers here:
Using global variables between files?
(9 answers)
Closed 2 years ago.
I would like to know please, how can I define variables in a python file and share these variables with their values with multiple python files?
To do this, you can create a new module specifically for storing all the global variables your application might need. For this you can create a function that will initialize any of these globals with a default value, you only need to call this function once from your main class, then you can import the globals file from any other class and use those globals as needed.
You can create a python module
Create a py file inside that module define variables and import that module in the required places.

How to "type" random package return [duplicate]

This question already has an answer here:
What is the type hint for a (any) python module?
(1 answer)
Closed 2 years ago.
I'm building an API to allow for plugins in an application I'm working on. I'm using importlib.import_module to import the plugins. Clearly I have no idea what modules are going to be imported ahead of time. Is there a way to identify the return type as a generic module on the method I'm using to do the imports?
def import_plugin(plugin_name: str) -> <Some generic module type>:
# conditional tests here...
return importlib.import_module("plugins.{}".format(plugin_name))
The type of a module is given by types.ModuleType in the types module.
import types
type(types) is types.ModuleType
# => True
Python uses duck typing, so I recommend assuming it is a module, and if it is not let the user handle it. If you really want to get the type, use types.ModuleType as khelwood said.

How to programatically add or delete names in a module [duplicate]

This question already has answers here:
dynamically adding functions to a Python module
(2 answers)
Closed 2 years ago.
Suppose I create a module on the fly:
import imp
my_module = imp.new_module('my_module')
and I want to add n similar names/value to this module, something that would be equivalent to
my_module.a1 = None
my_module.a2 = None
my_module.a3 = None
...
How can I access a module namespace like a dictionary (or in a similar way) so that I can write something like
for i in range(n):
my_module.some_env_like_dict[f"a{i}"] = None
Also how can I remove these names in a similar way?
I understand that Python may not have a recommended or official way of doing this. Obviously this is not for any serious project.
I'm looking for a solution that is more elegant than using exec.
I think what you're doing is essentially correct, with just a few additions:
my_module = imp.new_module('my_module')
my_module.var1 = 123
This creates a module, and sets var1 to 123 within the module. You can access it as my_module.var1 just as you would for any other module.
To access the attributes from strings, you can do:
val = getattr(my_module, "var1")
setattr(my_module, "var1", val + 1)
This sets val to 123, then updates var1 in my_module with the value 124. You can also add new attributes to the module in this manner.

Where is the right place to import libraries in an OOP code [duplicate]

This question already has answers here:
Should import statements always be at the top of a module?
(22 answers)
Closed 3 years ago.
let's say that I have a python file for some task written in OOP.
some classes in my code use libraries such as pandas, csv ...
Is it ok to import these libraries just before the main() function?
Technically it works but I'm not sure if this is the right way
class A
class B
class C
import csv
import pandas
def main ():
#pass
if __name__ == '__main__':
main()
PEP8 specifically describes where imports should go. Best to follow that.
Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.
EDIT TO ADD: You asked about import placement when programming OOP code. Assuming you're referring to Object Oriented Programming, that is a design pattern and has no bearing on the proper placement of imports. Imports are kept at the top of the module file to make it easy for anyone to easily see what dependencies a module has.
So, even if - to use your example - classes A, B, and C don't use csv or pandas, you'd still put those at the top because the module uses them even if some specific classes don't.

A solution to monkey patch any python module [duplicate]

This question already has answers here:
Monkey patching a class in another module in Python
(6 answers)
Closed 7 years ago.
I am in search for the right approach to monkey patch any function in a python module from within my app without modifying the modules package itself.
The background of my question is that my app is using Elasticsearch 2. ES 2 does not accept indexing of documents where fieldnames contain periods. Since my app uses pyes in multiple locations, I'd like to globally patch the indexing method and make sure that any period characters will be turned to underscore characters.
One of the best solution is using wrapper. Create a module and use the same name you want to patch, then in your sources use from mymodule import ES.
In this way, all requests comes to your module and you can decide to run the original or modify it.
another solution is patch in each step:
from pyes import ES
real_create_index = ES.indices.create_index
def create_index(self, idx_name):
# do what you need
real_create_index(self, idx_name)
ES.indices.create_index = create_index
from now on, whoever call conn.indices.create_index it will redirect to your code.

Categories

Resources