1660250100
Escribir código limpio y fácil de mantener es una tarea desafiante. Afortunadamente, hay muchos patrones, técnicas y soluciones reutilizables disponibles para hacer que lograr esa tarea sea mucho más fácil. La inyección de dependencia es una de esas técnicas, que se utiliza para escribir código débilmente acoplado pero altamente cohesivo.
En este artículo, le mostraremos cómo implementar la inyección de dependencias a medida que desarrolla una aplicación para trazar datos meteorológicos históricos. Después de desarrollar la aplicación inicial, mediante el desarrollo basado en pruebas, la refactorizará mediante la inserción de dependencias para desacoplar partes de la aplicación para que sea más fácil de probar, ampliar y mantener.
Al final de este artículo, debería poder explicar qué es la inyección de dependencia e implementarla en Python con desarrollo controlado por pruebas (TDD).
En ingeniería de software, la inyección de dependencia es una técnica en la que un objeto recibe otros objetos de los que depende.
Beneficios:
Para obtener más información, consulte el artículo Formas de inyección de dependencia de Martin Fowler .
To see it in action, let's take a look at a few real-world examples.
Scenario:
First, create (and activate) a virtual environment. Then, install pytest and Matplotlib:
(venv)$ pip install pytest matplotlib
It seems reasonable to start with a class with two methods:
read
- read data from a CSVdraw
- draw a plotSince we need to read historic weather data from a CSV file, the read
method should meet the following criteria:
App
classread
method is called with a CSV file name'%Y-%m-%dT%H:%M:%S.%f'
) and the values are temperatures measured at that momentCreate a file called test_app.py:
import datetime
from pathlib import Path
from app import App
BASE_DIR = Path(__file__).resolve(strict=True).parent
def test_read():
app = App()
for key, value in app.read(file_name=Path(BASE_DIR).joinpath('london.csv')).items():
assert datetime.datetime.fromisoformat(key)
assert value - 0 == value
So, this test checks that:
fromisoformat
function from datetime
package)x - 0 = x
)The
fromisoformat
method from thedatetime
package was added in Python 3.7. Refer to the official Python docs for more info.
Run the test to ensure it fails:
(venv)$ python -m pytest .
You should see:
E ModuleNotFoundError: No module named 'app'
Now to implement the read
method, to make the test pass, add new file called app.py:
import csv
import datetime
from pathlib import Path
BASE_DIR = Path(__file__).resolve(strict=True).parent
class App:
def read(self, file_name):
temperatures_by_hour = {}
with open(Path(BASE_DIR).joinpath(file_name), 'r') as file:
reader = csv.reader(file)
next(reader) # Skip header row.
for row in reader:
hour = datetime.datetime.strptime(row[0], '%d/%m/%Y %H:%M').isoformat()
temperature = float(row[2])
temperatures_by_hour[hour] = temperature
return temperatures_by_hour
Here, we added an App
class with a read
method that takes a file name as a parameter. After opening and reading the contents of the CSV, the appropriate keys (date) and values (temperature) are added to a dictionary which is eventually returned.
Assuming that you've downloaded the weather data as london.csv, the test should now pass:
(venv)$ python -m pytest .
================================ test session starts ====================================
platform darwin -- Python 3.10.0, pytest-6.2.5, py-1.11.0, pluggy-1.0.0
rootdir: /Users/michael.herman/repos/testdriven/dependency-injection-python/app
collected 1 item
test_app.py . [100%]
================================= 1 passed in 0.11s =====================================
Next, the draw
method should meet the following criteria:
App
classdraw
method is called with a dictionary where the keys are datetime strings in ISO 8601 format ('%Y-%m-%dT%H:%M:%S.%f'
) and the values are temperatures measured at that momentAdd a test for this to test_app.py:
def test_draw(monkeypatch):
plot_date_mock = MagicMock()
show_mock = MagicMock()
monkeypatch.setattr(matplotlib.pyplot, 'plot_date', plot_date_mock)
monkeypatch.setattr(matplotlib.pyplot, 'show', show_mock)
app = App()
hour = datetime.datetime.now().isoformat()
temperature = 14.52
app.draw({hour: temperature})
_, called_temperatures = plot_date_mock.call_args[0]
assert called_temperatures == [temperature] # check that plot_date was called with temperatures as second arg
show_mock.assert_called() # check that show is called
Update the imports like so:
import datetime
from pathlib import Path
from unittest.mock import MagicMock
import matplotlib.pyplot
from app import App
Since we don't want to show the actual plots during the test runs, we used monkeypatch
to mock the plot_date
function from matplotlib
. Then, the method under test is called with single temperature. At the end, we checked that plot_date
was called correctly (X and Y axis) and that show
was called.
You can read more about monkeypatching with pytest here and more about mocking here.
Let's move to the method implementation:
temperatures_by_hour
which should be dictionary of the same structure as the output from the read
method.matplotlib.dates.date2num
so they can be used in the plot.def draw(self, temperatures_by_hour):
dates = []
temperatures = []
for date, temperature in temperatures_by_hour.items():
dates.append(datetime.datetime.fromisoformat(date))
temperatures.append(temperature)
dates = matplotlib.dates.date2num(dates)
matplotlib.pyplot.plot_date(dates, temperatures, linestyle='-')
matplotlib.pyplot.show()
Imports:
import csv
import datetime
from pathlib import Path
import matplotlib.dates
import matplotlib.pyplot
The tests should now pass:
(venv)$ python -m pytest .
================================ test session starts ====================================
platform darwin -- Python 3.10.0, pytest-6.2.5, py-1.11.0, pluggy-1.0.0
rootdir: /Users/michael/repos/testdriven/python-dependency-injection
collected 2 items
test_app.py .. [100%]
================================= 2 passed in 0.37s =====================================
app.py:
import csv
import datetime
from pathlib import Path
import matplotlib.dates
import matplotlib.pyplot
BASE_DIR = Path(__file__).resolve(strict=True).parent
class App:
def read(self, file_name):
temperatures_by_hour = {}
with open(Path(BASE_DIR).joinpath(file_name), 'r') as file:
reader = csv.reader(file)
next(reader) # Skip header row.
for row in reader:
hour = datetime.datetime.strptime(row[0], '%d/%m/%Y %H:%M').isoformat()
temperature = float(row[2])
temperatures_by_hour[hour] = temperature
return temperatures_by_hour
def draw(self, temperatures_by_hour):
dates = []
temperatures = []
for date, temperature in temperatures_by_hour.items():
dates.append(datetime.datetime.fromisoformat(date))
temperatures.append(temperature)
dates = matplotlib.dates.date2num(dates)
matplotlib.pyplot.plot_date(dates, temperatures, linestyle='-')
matplotlib.pyplot.show()
test_app.py:
import datetime
from pathlib import Path
from unittest.mock import MagicMock
import matplotlib.pyplot
from app import App
BASE_DIR = Path(__file__).resolve(strict=True).parent
def test_read():
app = App()
for key, value in app.read(file_name=Path(BASE_DIR).joinpath('london.csv')).items():
assert datetime.datetime.fromisoformat(key)
assert value - 0 == value
def test_draw(monkeypatch):
plot_date_mock = MagicMock()
show_mock = MagicMock()
monkeypatch.setattr(matplotlib.pyplot, 'plot_date', plot_date_mock)
monkeypatch.setattr(matplotlib.pyplot, 'show', show_mock)
app = App()
hour = datetime.datetime.now().isoformat()
temperature = 14.52
app.draw({hour: temperature})
_, called_temperatures = plot_date_mock.call_args[0]
assert called_temperatures == [temperature] # check that plot_date was called with temperatures as second arg
show_mock.assert_called() # check that show is called
You have all that you need to run your application for plotting temperatures by hour form the selected CSV file.
Let's make our app runnable.
Open app.py and add following snippet to the bottom:
if __name__ == '__main__':
import sys
file_name = sys.argv[1]
app = App()
temperatures_by_hour = app.read(file_name)
app.draw(temperatures_by_hour)
When app.py runs, it first reads the CSV file from the command line argument assigned to file_name
and then it draws the plot.
Run the app:
(venv)$ python app.py london.csv
You should see a plot like this:
If you encounter
Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure.
, check this Stack Overflow answer.
Alright. We finished our initial iteration of our app for plotting historical weather data. It's working as expected and we're happy to use it. That said, it's tightly coupled with a CSV. What if you wanted to use a different data format? Like a JSON payload from an API. This is where Dependency Injection comes into play.
Let's separate the reading part from our main app.
First, create new file called test_urban_climate_csv.py:
import datetime
from pathlib import Path
from app import App
from urban_climate_csv import DataSource
BASE_DIR = Path(__file__).resolve(strict=True).parent
def test_read():
app = App()
for key, value in app.read(file_name=Path(BASE_DIR).joinpath('london.csv')).items():
assert datetime.datetime.fromisoformat(key)
assert value - 0 == value
The test here is the same as our test for test_read
in test_app.py.
Second, add a new file called urban_climate_csv.py. Inside that file, create a class called DataSource
with a read
method:
import csv
import datetime
from pathlib import Path
BASE_DIR = Path(__file__).resolve(strict=True).parent
class DataSource:
def read(self, **kwargs):
temperatures_by_hour = {}
with open(Path(BASE_DIR).joinpath(kwargs['file_name']), 'r') as file:
reader = csv.reader(file)
next(reader) # Skip header row.
for row in reader:
hour = datetime.datetime.strptime(row[0], '%d/%m/%Y %H:%M').isoformat()
temperature = float(row[2])
temperatures_by_hour[hour] = temperature
return temperatures_by_hour
This is same as the read
method in our initial app with one difference: We're using kwargs
because we want to have the same interface for all our data sources. So, we could add new readers as necessary based on the source of the data.
For example:
from open_weather_csv import DataSource
from open_weather_json import DataSource
from open_weather_api import DataSource
csv_reader = DataSource()
reader.read(file_name='foo.csv')
json_reader = DataSource()
reader.read(file_name='foo.json')
api_reader = DataSource()
reader.read(url='https://foo.bar')
The test should now pass:
(venv)$ python -m pytest .
================================ test session starts ====================================
platform darwin -- Python 3.10.0, pytest-6.2.5, py-1.11.0, pluggy-1.0.0
rootdir: /Users/michael/repos/testdriven/python-dependency-injection
collected 2 items
test_app.py .. [ 66%]
test_urban_climate_csv.py . [100%]
================================= 3 passed in 0.48s =====================================
Now, we need to update our App
class.
First, update the test for read
in test_app.py:
def test_read():
hour = datetime.datetime.now().isoformat()
temperature = 14.52
temperature_by_hour = {hour: temperature}
data_source = MagicMock()
data_source.read.return_value = temperature_by_hour
app = App(
data_source=data_source
)
assert app.read(file_name='something.csv') == temperature_by_hour
So what changed? We injected data_source
to our App
. This simplifies testing as the read
method has a single job: to return results from the data source. This is an example of the first benefit of Dependency Injection: Testing is easier since we can inject the underlying dependencies.
Update the test for draw
too. Again, we need to inject the data source to App
, which can be "anything" with an expected interface -- so MagicMock will do:
def test_draw(monkeypatch):
plot_date_mock = MagicMock()
show_mock = MagicMock()
monkeypatch.setattr(matplotlib.pyplot, 'plot_date', plot_date_mock)
monkeypatch.setattr(matplotlib.pyplot, 'show', show_mock)
app = App(MagicMock())
hour = datetime.datetime.now().isoformat()
temperature = 14.52
app.draw({hour: temperature})
_, called_temperatures = plot_date_mock.call_args[0]
assert called_temperatures == [temperature] # check that plot_date was called with temperatures as second arg
show_mock.assert_called() # check that show is called
Update the App
class as well:
import datetime
import matplotlib.dates
import matplotlib.pyplot
class App:
def __init__(self, data_source):
self.data_source = data_source
def read(self, **kwargs):
return self.data_source.read(**kwargs)
def draw(self, temperatures_by_hour):
dates = []
temperatures = []
for date, temperature in temperatures_by_hour.items():
dates.append(datetime.datetime.fromisoformat(date))
temperatures.append(temperature)
dates = matplotlib.dates.date2num(dates)
matplotlib.pyplot.plot_date(dates, temperatures, linestyle='-')
matplotlib.pyplot.show(block=True)
First, we added an __init__
method so the data source can be injected. Second, we updated the read
method to use self.data_source
and **kwargs
. Look at how much simpler this interface is. App
is no longer coupled with the reading of the data anymore.
Finally, we need to inject our data source to App
on instance creation.
if __name__ == '__main__':
import sys
from urban_climate_csv import DataSource
file_name = sys.argv[1]
app = App(DataSource())
temperatures_by_hour = app.read(file_name=file_name)
app.draw(temperatures_by_hour)
Run your app again to ensure it still works as expected:
(venv)$ python app.py london.csv
Update test_read
in test_urban_climate_csv.py:
import datetime
from urban_climate_csv import DataSource
def test_read():
reader = DataSource()
for key, value in reader.read(file_name='london.csv').items():
assert datetime.datetime.fromisoformat(key)
assert value - 0 == value
Do the tests pass?
(venv)$ python -m pytest .
================================ test session starts ====================================
platform darwin -- Python 3.10.0, pytest-6.2.5, py-1.11.0, pluggy-1.0.0
rootdir: /Users/michael/repos/testdriven/python-dependency-injection
collected 2 items
test_app.py .. [ 66%]
test_urban_climate_csv.py . [100%]
================================= 3 passed in 0.40s =====================================
Now that we've decoupled our App
from the data source, we can easily add a new source.
Let's use data from the OpenWeather API. Go ahead and download a pre-downloaded response from the API: here. Save it as moscow.json.
Feel free to register with the OpenWeather API and grab historical data for a different city if you'd prefer.
Add a new file called test_open_weather_json.py, and write a test for a read
method:
import datetime
from open_weather_json import DataSource
def test_read():
reader = DataSource()
for key, value in reader.read(file_name='moscow.json').items():
assert datetime.datetime.fromisoformat(key)
assert value - 0 == value
Since we're using the same interface to apply Dependency Injection, this test should look very similar to test_read
in test_urban_climate_csv.
In statically-typed languages, like Java and C#, all data sources should implement the same interface -- i.e., IDataSource
. Thanks to duck typing in Python, we can just implement methods with the same name that takes the same arguments (**kwargs
) for each of our data sources:
def read(self, **kwargs):
return self.data_source.read(**kwargs)
Next, let's move on to implementation.
Add new file called open_weather_json.py.:
import json
import datetime
class DataSource:
def read(self, **kwargs):
temperatures_by_hour = {}
with open(kwargs['file_name'], 'r') as file:
json_data = json.load(file)['hourly']
for row in json_data:
hour = datetime.datetime.fromtimestamp(row['dt']).isoformat()
temperature = float(row['temp'])
temperatures_by_hour[hour] = temperature
return temperatures_by_hour
So, we used the json
module to read and load a JSON file. Then, we extracted the data in a similar manner as we did before. This time we used the fromtimestamp
function because times of measurements are written in Unix timestamp format.
The tests should pass.
Next, update app.py to use this data source instead:
if __name__ == '__main__':
import sys
from open_weather_json import DataSource
file_name = sys.argv[1]
app = App(DataSource())
temperatures_by_hour = app.read(file_name=file_name)
app.draw(temperatures_by_hour)
Here, we just changed the import.
Run your app again with moscow.json as the argument:
(venv)$ python app.py moscow.json
You should see a plot with data from the selected JSON file.
This is an example of the second benefit of Dependency Injection: Extending code is much simpler.
We can see that:
App
classSo, we can now extend the codebase with simple and predictable steps without having to touch tests that are already written or change the main application. That's powerful. You could now have a developer focus solely on adding new data sources without them ever needing to understand or have context on the main application. That said, if you do need to onboard a new developer who does need to have context on the entire project, it can take longer for them to get up to speed due to the decoupling.
Moving right along, let's decouple the plotting portion from the app so we can more easily add new plotting libraries. Since this will be a similar process to the data source decoupling, think through the steps on your own before reading the rest of this section.
Take a look at the test for the draw
method in test_app.py:
def test_draw(monkeypatch):
plot_date_mock = MagicMock()
show_mock = MagicMock()
monkeypatch.setattr(matplotlib.pyplot, 'plot_date', plot_date_mock)
monkeypatch.setattr(matplotlib.pyplot, 'show', show_mock)
app = App(MagicMock())
hour = datetime.datetime.now().isoformat()
temperature = 14.52
app.draw({hour: temperature})
_, called_temperatures = plot_date_mock.call_args[0]
assert called_temperatures == [temperature] # check that plot_date was called with temperatures as second arg
show_mock.assert_called() # check that show is called
As we can see, it's coupled with Matplotlib. A change to the plotting library will require a change to the tests. This is something you really want to avoid.
So, how can we improve this?
Let's extract the plotting part of our app into its own class much like we did for the reading in of the data source.
Add a new file called test_matplotlib_plot.py:
import datetime
from unittest.mock import MagicMock
import matplotlib.pyplot
from matplotlib_plot import Plot
def test_draw(monkeypatch):
plot_date_mock = MagicMock()
show_mock = MagicMock()
monkeypatch.setattr(matplotlib.pyplot, 'plot_date', plot_date_mock)
monkeypatch.setattr(matplotlib.pyplot, 'show', show_mock)
plot = Plot()
hours = [datetime.datetime.now()]
temperatures = [14.52]
plot.draw(hours, temperatures)
_, called_temperatures = plot_date_mock.call_args[0]
assert called_temperatures == temperatures # check that plot_date was called with temperatures as second arg
show_mock.assert_called() # check that show is called
To implement the Plot
class, add a new file called matplotlib_plot.py:
import matplotlib.dates
import matplotlib.pyplot
class Plot:
def draw(self, hours, temperatures):
hours = matplotlib.dates.date2num(hours)
matplotlib.pyplot.plot_date(hours, temperatures, linestyle='-')
matplotlib.pyplot.show(block=True)
Here, the draw
method takes two arguments:
hours
- a list of datetime objectstemperatures
- a list of numbersThis is what our interface will look like for all future Plot
classes. So, in this case, our test will stay the same as long as this interface and the underlying matplotlib
methods stay the same.
Run the tests:
(venv)$ python -m pytest .
================================ test session starts ====================================
platform darwin -- Python 3.10.0, pytest-6.2.5, py-1.11.0, pluggy-1.0.0
rootdir: /Users/michael/repos/testdriven/python-dependency-injection
collected 2 items
test_app.py .. [ 40%]
test_matplotlib_plot.py . [ 60%]
test_open_weather_json.py . [ 80%]
test_urban_climate_csv.py . [100%]
================================= 5 passed in 0.38s =====================================
Next, let's update the App
class.
First, update test_app.py like so:
import datetime
from unittest.mock import MagicMock
from app import App
def test_read():
hour = datetime.datetime.now().isoformat()
temperature = 14.52
temperature_by_hour = {hour: temperature}
data_source = MagicMock()
data_source.read.return_value = temperature_by_hour
app = App(
data_source=data_source,
plot=MagicMock()
)
assert app.read(file_name='something.csv') == temperature_by_hour
def test_draw():
plot_mock = MagicMock()
app = App(
data_source=MagicMock,
plot=plot_mock
)
hour = datetime.datetime.now()
iso_hour = hour.isoformat()
temperature = 14.52
temperature_by_hour = {iso_hour: temperature}
app.draw(temperature_by_hour)
plot_mock.draw.assert_called_with([hour], [temperature])
Since test_draw
is no longer coupled with Matplotlib, we injected plot to App
before calling the draw
method. As long as the interface of the injected Plot
is as expected the test should pass. Therefore, we can use MagicMock
in our test. We then checked that the draw
method was called as expected. We also injected the plot into test_read
. That's all.
Update the App
class:
import datetime
class App:
def __init__(self, data_source, plot):
self.data_source = data_source
self.plot = plot
def read(self, **kwargs):
return self.data_source.read(**kwargs)
def draw(self, temperatures_by_hour):
dates = []
temperatures = []
for date, temperature in temperatures_by_hour.items():
dates.append(datetime.datetime.fromisoformat(date))
temperatures.append(temperature)
self.plot.draw(dates, temperatures)
The refactored draw
method is much simpler now. It just:
draw
method of of the Plot
instanceTest:
(venv)$ python -m pytest .
================================ test session starts ====================================
platform darwin -- Python 3.10.0, pytest-6.2.5, py-1.11.0, pluggy-1.0.0
rootdir: /Users/michael/repos/testdriven/python-dependency-injection
collected 2 items
test_app.py .. [ 40%]
test_matplotlib_plot.py . [ 60%]
test_open_weather_json.py . [ 80%]
test_urban_climate_csv.py . [100%]
================================= 5 passed in 0.39s =====================================
Update the snippet for running the app again:
if __name__ == '__main__':
import sys
from open_weather_json import DataSource
from matplotlib_plot import Plot
file_name = sys.argv[1]
app = App(DataSource(), Plot())
temperatures_by_hour = app.read(file_name=file_name)
app.draw(temperatures_by_hour)
We added a new import for Plot
and injeced it into App
.
Run your app again to see that it's still working:
(venv)$ python app.py moscow.json
Start by installing Plotly:
(venv)$ pip install plotly
Next, add a new test to a new filed called test_plotly_plot.py:
import datetime
from unittest.mock import MagicMock
import plotly.graph_objects
from plotly_plot import Plot
def test_draw(monkeypatch):
figure_mock = MagicMock()
monkeypatch.setattr(plotly.graph_objects, 'Figure', figure_mock)
scatter_mock = MagicMock()
monkeypatch.setattr(plotly.graph_objects, 'Scatter', scatter_mock)
plot = Plot()
hours = [datetime.datetime.now()]
temperatures = [14.52]
plot.draw(hours, temperatures)
call_kwargs = scatter_mock.call_args[1]
assert call_kwargs['y'] == temperatures # check that plot_date was called with temperatures as second arg
figure_mock().show.assert_called() # check that show is called
It's basically the same as the matplotlib Plot
test. The major change is how the objects and methods from Plotly are mocked.
Second, add file called plotly_plot.py:
import plotly.graph_objects
class Plot:
def draw(self, hours, temperatures):
fig = plotly.graph_objects.Figure(
data=[plotly.graph_objects.Scatter(x=hours, y=temperatures)]
)
fig.show()
Aquí, solíamos plotly
dibujar un gráfico con fechas. Eso es todo.
Las pruebas deben pasar:
(venv)$ python -m pytest .
================================ test session starts ====================================
platform darwin -- Python 3.10.0, pytest-6.2.5, py-1.11.0, pluggy-1.0.0
rootdir: /Users/michael/repos/testdriven/python-dependency-injection
collected 6 items
test_app.py .. [ 33%]
test_matplotlib_plot.py . [ 50%]
test_open_weather_json.py . [ 66%]
test_plotly_plot.py . [ 83%]
test_urban_climate_csv.py . [100%]
================================= 6 passed in 0.46s =====================================
Actualice el fragmento de ejecución para usar plotly
:
if __name__ == '__main__':
import sys
from open_weather_json import DataSource
from plotly_plot import Plot
file_name = sys.argv[1]
app = App(DataSource(), Plot())
temperatures_by_hour = app.read(file_name=file_name)
app.draw(temperatures_by_hour)
Ejecute su aplicación con moscow.json para ver la nueva trama en su navegador:
(venv)$ python app.py moscow.json
En este punto, podemos agregar y usar fácilmente diferentes fuentes de datos y bibliotecas de gráficos en nuestra aplicación. Nuestras pruebas ya no se combinan con la implementación. Dicho esto, todavía tenemos que editar el código para agregar una nueva fuente de datos o biblioteca de trazado:
if __name__ == '__main__':
import sys
from open_weather_json import DataSource
from plotly_plot import Plot
file_name = sys.argv[1]
app = App(DataSource(), Plot())
temperatures_by_hour = app.read(file_name=file_name)
app.draw(temperatures_by_hour)
Aunque es solo un pequeño fragmento de código, podemos llevar la inyección de dependencia un paso más allá y eliminar la necesidad de cambios en el código. En su lugar, usaremos un archivo de configuración para seleccionar la fuente de datos y la biblioteca de trazado.
Usaremos un objeto JSON simple para configurar nuestra aplicación:
{
"data_source": {
"name": "urban_climate_csv"
},
"plot": {
"name": "plotly_plot"
}
}
Agregue esto a un nuevo archivo llamado config.json .
Agregue una nueva prueba a test_app.py :
def test_configure():
app = App.configure(
'config.json'
)
assert isinstance(app, App)
Aquí, verificamos que el método App
devuelva una instancia de. configure
Este método leerá el archivo de configuración y cargará el archivo seleccionado DataSource
y Plot
.
Añadir configure
a la App
clase:
import datetime
import json
class App:
...
@classmethod
def configure(cls, filename):
with open(filename) as file:
config = json.load(file)
data_source = __import__(config['data_source']['name']).DataSource()
plot = __import__(config['plot']['name']).Plot()
return cls(data_source, plot)
if __name__ == '__main__':
import sys
from open_weather_json import DataSource
from plotly_plot import Plot
file_name = sys.argv[1]
app = App(DataSource(), Plot())
temperatures_by_hour = app.read(file_name=file_name)
app.draw(temperatures_by_hour)
Entonces, después de cargar el archivo JSON, importamos DataSource
y Plot
desde los respectivos módulos definidos en el archivo de configuración.
__import__
se utiliza para importar módulos dinámicamente. Por ejemplo, establecer config['data_source']['name']
a urban_climate_csv
es equivalente a:
import urban_climate_csv
data_source = urban_climate_csv.DataSource()
Ejecute las pruebas:
(venv)$ python -m pytest .
================================ test session starts ====================================
platform darwin -- Python 3.10.0, pytest-6.2.5, py-1.11.0, pluggy-1.0.0
rootdir: /Users/michael/repos/testdriven/python-dependency-injection
collected 6 items
test_app.py ... [ 42%]
test_matplotlib_plot.py . [ 57%]
test_open_weather_json.py . [ 71%]
test_plotly_plot.py . [ 85%]
test_urban_climate_csv.py . [100%]
================================= 6 passed in 0.46s =====================================
Finalmente, actualice el fragmento en app.py para usar el método recién agregado:
if __name__ == '__main__':
import sys
config_file = sys.argv[1]
file_name = sys.argv[2]
app = App.configure(config_file)
temperatures_by_hour = app.read(file_name=file_name)
app.draw(temperatures_by_hour)
Con las importaciones eliminadas, puede cambiar rápidamente una fuente de datos o una biblioteca de gráficos por otra.
Ejecute su aplicación una vez más:
(venv)$ python app.py config.json london.csv
Actualice la configuración para usarla open_weather_json
como fuente de datos:
{
"data_source": {
"name": "open_weather_json"
},
"plot": {
"name": "plotly_plot"
}
}
Ejecute la aplicación:
(venv)$ python app.py config.json moscow.json
La App
clase principal comenzó como un objeto omnisciente responsable de leer datos de un CSV y dibujar un diagrama. Utilizamos Inyección de dependencia para desacoplar la funcionalidad de lectura y dibujo. La App
clase ahora es un contenedor con una interfaz simple que conecta las partes de lectura y dibujo. La lógica real de lectura y dibujo se maneja en clases especializadas que son responsables de una sola cosa.
Beneficios:
¿Hicimos algo especial? Realmente no. La idea detrás de la inyección de dependencia es bastante común en el mundo de la ingeniería, fuera de la ingeniería de software.
Por ejemplo, un carpintero que construye el exterior de una casa generalmente dejará espacios vacíos para ventanas y puertas para que alguien especializado específicamente en la instalación de puertas y ventanas pueda instalarlos. Cuando la casa esté completa y los propietarios se muden, ¿necesitarán derribar la mitad de la casa solo para cambiar una ventana existente? No. Solo pueden arreglar la ventana rota. Siempre que las ventanas tengan la misma interfaz (por ejemplo, ancho, alto, profundidad, etc.), pueden instalarlas y usarlas. ¿Pueden abrir la ventana antes de instalarla? Por supuesto. ¿Pueden probar si la ventana está rota antes de instalarla? Sí. También es una forma de inyección de dependencia.
Puede que no sea tan natural ver y usar la inyección de dependencia en la ingeniería de software, pero es tan eficaz como en cualquier otra profesión de ingeniería.
¿Buscando por mas?
open_weather_api
. Esta fuente toma una ciudad, realiza la llamada a la API y luego devuelve los datos en la forma correcta para el draw
método.Este artículo mostró cómo implementar la inyección de dependencia en una aplicación del mundo real.
Aunque es una técnica poderosa, la inyección de dependencia no es una panacea. Piense de nuevo en la analogía de la casa: el caparazón de la casa y las ventanas y puertas están débilmente acoplados. ¿Se puede decir lo mismo de una tienda de campaña? No. Si la puerta de la tienda está dañada sin posibilidad de reparación, probablemente querrá comprar una tienda nueva en lugar de tratar de reparar la puerta dañada. Por lo tanto, no puede desacoplarse y aplicar Inyección de dependencia a todo. De hecho, puede arrastrarlo al infierno de la optimización prematura si se hace demasiado pronto. Aunque es más fácil de mantener, hay más superficie y el código desacoplado puede ser más difícil de entender para los recién llegados al proyecto.
Entonces, antes de lanzarte, pregúntate:
Si puede responder fácilmente a estas preguntas y los beneficios superan los inconvenientes, hágalo. De lo contrario, puede que no sea adecuado usarlo en este momento.
¡Feliz codificación!
Fuente: https://testdriven.io
1619510796
Welcome to my Blog, In this article, we will learn python lambda function, Map function, and filter function.
Lambda function in python: Lambda is a one line anonymous function and lambda takes any number of arguments but can only have one expression and python lambda syntax is
Syntax: x = lambda arguments : expression
Now i will show you some python lambda function examples:
#python #anonymous function python #filter function in python #lambda #lambda python 3 #map python #python filter #python filter lambda #python lambda #python lambda examples #python map
1626775355
No programming language is pretty much as diverse as Python. It enables building cutting edge applications effortlessly. Developers are as yet investigating the full capability of end-to-end Python development services in various areas.
By areas, we mean FinTech, HealthTech, InsureTech, Cybersecurity, and that's just the beginning. These are New Economy areas, and Python has the ability to serve every one of them. The vast majority of them require massive computational abilities. Python's code is dynamic and powerful - equipped for taking care of the heavy traffic and substantial algorithmic capacities.
Programming advancement is multidimensional today. Endeavor programming requires an intelligent application with AI and ML capacities. Shopper based applications require information examination to convey a superior client experience. Netflix, Trello, and Amazon are genuine instances of such applications. Python assists with building them effortlessly.
Python can do such numerous things that developers can't discover enough reasons to admire it. Python application development isn't restricted to web and enterprise applications. It is exceptionally adaptable and superb for a wide range of uses.
Robust frameworks
Python is known for its tools and frameworks. There's a structure for everything. Django is helpful for building web applications, venture applications, logical applications, and mathematical processing. Flask is another web improvement framework with no conditions.
Web2Py, CherryPy, and Falcon offer incredible capabilities to customize Python development services. A large portion of them are open-source frameworks that allow quick turn of events.
Simple to read and compose
Python has an improved sentence structure - one that is like the English language. New engineers for Python can undoubtedly understand where they stand in the development process. The simplicity of composing allows quick application building.
The motivation behind building Python, as said by its maker Guido Van Rossum, was to empower even beginner engineers to comprehend the programming language. The simple coding likewise permits developers to roll out speedy improvements without getting confused by pointless subtleties.
Utilized by the best
Alright - Python isn't simply one more programming language. It should have something, which is the reason the business giants use it. Furthermore, that too for different purposes. Developers at Google use Python to assemble framework organization systems, parallel information pusher, code audit, testing and QA, and substantially more. Netflix utilizes Python web development services for its recommendation algorithm and media player.
Massive community support
Python has a steadily developing community that offers enormous help. From amateurs to specialists, there's everybody. There are a lot of instructional exercises, documentation, and guides accessible for Python web development solutions.
Today, numerous universities start with Python, adding to the quantity of individuals in the community. Frequently, Python designers team up on various tasks and help each other with algorithmic, utilitarian, and application critical thinking.
Progressive applications
Python is the greatest supporter of data science, Machine Learning, and Artificial Intelligence at any enterprise software development company. Its utilization cases in cutting edge applications are the most compelling motivation for its prosperity. Python is the second most well known tool after R for data analytics.
The simplicity of getting sorted out, overseeing, and visualizing information through unique libraries makes it ideal for data based applications. TensorFlow for neural networks and OpenCV for computer vision are two of Python's most well known use cases for Machine learning applications.
Thinking about the advances in programming and innovation, Python is a YES for an assorted scope of utilizations. Game development, web application development services, GUI advancement, ML and AI improvement, Enterprise and customer applications - every one of them uses Python to its full potential.
The disadvantages of Python web improvement arrangements are regularly disregarded by developers and organizations because of the advantages it gives. They focus on quality over speed and performance over blunders. That is the reason it's a good idea to utilize Python for building the applications of the future.
#python development services #python development company #python app development #python development #python in web development #python software development
1602968400
Python is awesome, it’s one of the easiest languages with simple and intuitive syntax but wait, have you ever thought that there might ways to write your python code simpler?
In this tutorial, you’re going to learn a variety of Python tricks that you can use to write your Python code in a more readable and efficient way like a pro.
Swapping value in Python
Instead of creating a temporary variable to hold the value of the one while swapping, you can do this instead
>>> FirstName = "kalebu"
>>> LastName = "Jordan"
>>> FirstName, LastName = LastName, FirstName
>>> print(FirstName, LastName)
('Jordan', 'kalebu')
#python #python-programming #python3 #python-tutorials #learn-python #python-tips #python-skills #python-development
1602666000
Today you’re going to learn how to use Python programming in a way that can ultimately save a lot of space on your drive by removing all the duplicates.
In many situations you may find yourself having duplicates files on your disk and but when it comes to tracking and checking them manually it can tedious.
Heres a solution
Instead of tracking throughout your disk to see if there is a duplicate, you can automate the process using coding, by writing a program to recursively track through the disk and remove all the found duplicates and that’s what this article is about.
But How do we do it?
If we were to read the whole file and then compare it to the rest of the files recursively through the given directory it will take a very long time, then how do we do it?
The answer is hashing, with hashing can generate a given string of letters and numbers which act as the identity of a given file and if we find any other file with the same identity we gonna delete it.
There’s a variety of hashing algorithms out there such as
#python-programming #python-tutorials #learn-python #python-project #python3 #python #python-skills #python-tips
1597751700
Magic Methods are the special methods which gives us the ability to access built in syntactical features such as ‘<’, ‘>’, ‘==’, ‘+’ etc…
You must have worked with such methods without knowing them to be as magic methods. Magic methods can be identified with their names which start with __ and ends with __ like init, call, str etc. These methods are also called Dunder Methods, because of their name starting and ending with Double Underscore (Dunder).
Now there are a number of such special methods, which you might have come across too, in Python. We will just be taking an example of a few of them to understand how they work and how we can use them.
class AnyClass:
def __init__():
print("Init called on its own")
obj = AnyClass()
The first example is _init, _and as the name suggests, it is used for initializing objects. Init method is called on its own, ie. whenever an object is created for the class, the init method is called on its own.
The output of the above code will be given below. Note how we did not call the init method and it got invoked as we created an object for class AnyClass.
Init called on its own
Let’s move to some other example, add gives us the ability to access the built in syntax feature of the character +. Let’s see how,
class AnyClass:
def __init__(self, var):
self.some_var = var
def __add__(self, other_obj):
print("Calling the add method")
return self.some_var + other_obj.some_var
obj1 = AnyClass(5)
obj2 = AnyClass(6)
obj1 + obj2
#python3 #python #python-programming #python-web-development #python-tutorials #python-top-story #python-tips #learn-python