A very good evening aspirants. Before getting into the news article discussion, I have an announcement for you to know. See, clearing prylums is a mammoth task for many. But why worry when you have Shankarayesh academy? See, our pre-storming program is aimed to facilitate this process. Pre-storming is the most reliable prylums to series offered by Shankarayesh academy. Already two batches are going on successfully. Now for those who have missed to enrol in these batches, a third chance is awaiting. Yes, pre-storming batch 3 is starting on November 9th. The first test in this batch will commence on 20th November. Like the other batches, it will also have 66 tests. So go and register today to enhance your prylums score. So with this announcement, now let us move on to the Hindu newspaper analysis. Today's date is 6th November 2022. Displayed here are the list of news articles that we are going to discuss today. So without much delay, let's get into the first news article discussion. Now look at this question corner article from the science and technology page. The question asked today is why do puffer fish spawn on beaches under moonlight? See, to understand the answer for this question, we have to know We have to know what is spawning and what are pheromones? See, spawning is a process of release or deposit of eggs by organisms like fish and frogs. And pheromones are hormones like chemicals. The difference between both is that, while hormones are released inside the body, the pheromones are released outside the body. The next difference is that, while hormones are chemical signals for our body's internal organs to communicate with itself, the pheromones are chemical signals used to communicate with other organisms of the same species. So now coming back to the question, why do puffer fish spawn on beaches under moonlight? See, the puffer fish normally spawn along the coast at night during springtime. After studying the genetic makeup of the puffer fish, the scientists concluded that this behavior is due to a release of a particular pheromone called PGE2. See, using this pheromone PGE2, the puffer fish communicate with each other and perform synchronized beach spawning. So, this is about the puffer fish and its spawning behavior. Now, while discussing about the behavior of the puffer fish, I mentioned that puffer fish normally spawn along the coast at night during springtime. And here, what are the springtides? See, first of all, tides are a periodic rise and fall in sea level due to the gravitational force exerted by the moon and the sun. In case of tides, it is the gravitational effect of the moon that plays an important role and the gravitational effect of the sun plays only a minor role. See, we know that our moon revolves around the earth and it takes four weeks for our moon to complete one revolution around the earth, right? So, whenever moon revolves around the earth, at two moments, the earth, sun and the moon fall in the same line. Once, when the earth is between the sun and the moon and again when the moon is between the sun and the earth. So, when the earth is between the sun and moon, we get that full moon day. Again, when the moon is between sun and earth, we get the new moon day. So, in both the cases, the gravitational pull of the sun is added to gravitational pull of the moon on earth. This will cause the oceans to bulge a bit more than usual. This is called the springtide. We know that every coastal area experiences two high tides and two low tides every day due to the rotation of the earth, right?  But what happens when the sun and moon are at right angle to each other? See, when this happens, the bulge of the ocean caused by the sun partially cancels out the bulge of the ocean caused by the moon. This produces moderate tides known as neeptides.  An additional point to note here is that for every lunar month, our earth experiences two springtides and two neeptides. So, that's all you have to know about this question corner article from the Science and Tech page. So, in this news article discussion, we could able to understand why do puffer fish span on beaches under moonlight. Then we also understood the difference between the springtide and neeptide. So, with these learnt points, now let us move on to the next news article discussion. Now, let us take up this news article. This news article talks about enforcement direct rate that is ED. See, yesterday, the ED had questioned the personal assistant of Delhi's deputy chief minister. The investigation is conducted in connection with the money laundering probe in the implementation of Delhi's exercise policy 2021-22. The ED also conducted searches at five locations in and around Delhi in connection with the case. So, this is the crux of the news article given here. So, in this context, let us learn few points about the enforcement direct rate or ED and its functions. See, the enforcement direct rate or direct rate of enforcement is a law enforcement and specialized financial investigation agency. It functions under the department of revenue of the ministry of finance. The enforcement direct rate is headquartered at New Delhi and it is headed by the director of enforcement. It also has five regional officers headed at Mumbai, Chennai, Chandigarh, Kolkata and Delhi. And each regional office is headed by special directors of enforcement. Also know that ED also has officers at zonal levels and they are headed by a joint director. So, this is the institutional setup of ED. Now, coming to their functions. See, ED is a multidisciplinary organization and it is mandated with investigation of offenses of money laundering and violations of foreign exchange laws. Now, we will see those laws and the statutory functions of ED under those laws. Firstly, the prevention of money laundry act which is in short called as PMLA. See, it is a criminal law enacted to prevent money laundering. The law provides for confiscation and attachment of property which is involved in money laundering. Here, the ED has been given the responsibility to enforce the provisions of the PMLA. The ED will conduct the investigation to trace the assets derived from money laundering and it confiscates those assets. Then, ED also ensures the prosecution of the offenders under PMLA. Secondly, the foreign exchange management act 1999 which is in short called as FEMI. See, it is a civil law enacted to consolidate and amend the laws relating to external trade and payments. This FEMI Act also promotes the orderly development and maintenance of foreign exchange market in India. Here, the ED has been given the responsibility to conduct investigation. See, the investigation is conducted on suspected contraventions of foreign exchange laws and regulations. See, under FEMI Act, ED also has the powers to adjudicate and impose penalties on those who have contravened the law. And finally, the fugitive economic offenders act 2018 which is in short called as FEMOA. See, this act was enacted to deter fugitive economic offender. Now, what does this term fugitive economic offender mean? See, if a person has left India to avoid criminal prosecution and if he or she refuses to return to India to face criminal prosecution, then they are defined as fugitive economic offenders. Here, the ED is mandated to attach the properties of the fugitive economic offenders who have escaped from India. And by warranting arrest, ED provide for the confiscation of fugitive economic offenders properties to the central government. So, these are all very important points that you have to make note of with respect to enforcement direct trade. So, in this news article discussion, we saw in detail about enforcement direct trade and its functions. With these learned points, now let us move on to the next news article discussion. Now, look at this news article. It is about the warning given by UNESCO. See, this news article says that one-third of the glaciers on the UNESCO's World Heritage List are under threat. And it is found that the threat will continue despite the efforts to limit temperature increases. And this is about the news article given here. In this context, let us see the important points mentioned in the UNESCO report and also the significance of glaciers. So, now let us begin with the significance of glacier. So, why should we conserve them? See, the major reason is that glaciers cover about 10 percentage of planet's surface and they are crucial for sustaining life on earth. We will see why they are crucial. The first reason is that glacial ecosystems provide ecosystem services like sediment sinks, freshwater reservoirs and we use this freshwater for domestic use, agriculture, industry and hydropower generation. Now that glaciers are called as water towers. This is because glaciers in mountains provide low lands with essential freshwater supply. So, this is the first reason why glacial ecosystem is very important. The second reason is that glaciers serve as habitat for biodiversity. See, about 50 percentage of the global biodiversity hotspots on the planet are located in basins drained by glaciers and also know that they contain one-third of the entire terrestrial species diversity. The third reason is that glacier ice feed the great rivers of Central Asia, South Asia and Southeast Asia and fourthly they serve as a global thermostat by regulating ozone circulation and they reduce the global temperature. See, the white ice cover cools the earth by reflecting sunlight. We call this as albedo effect. So, this means that glaciers play an important role in the global climate system itself. Now finally, glaciers carry huge cultural and spiritual significance for many indigenous people and local communities. See, they provide economic and educational benefits through the recreation and tourism. So, now these are the reasons why we should conserve glaciers and icebergs. Now, coming to the article, it said that around 18,600 glaciers have been identified in 50 world heritage sites and it is also found that world heritage glaciers lose on average some 58 billion tons of ice every year and they contribute to almost 5 percentage of global observed sea level rise and projections indicate that glaciers in one-third of world heritage sites will disappear by 2050 regardless of the applied climate scenario. So, the UNESCO report says that to stop glacier retreat, we have to drastically reduce greenhouse gas emissions. If emissions are cut to limit global warming to 1.5 degree Celsius, then glaciers in two-third of world heritage sites could be saved. So, that is all you have to know about from this news article discussion. In this news article discussion, we saw in detail about the significance of glaciers and why we have to conserve them. Along with that, we saw some of the facts that are mentioned in the UNESCO report. See, you can quote these facts in your main sansa writing. That is why I am explaining you with all the data included, okay? So, these learned points. Now, let us move on to the next news article discussion. Now, look at this news article. This news article talks about the use of inhaled vaccines to stop and prevent the spread of SARS-CoV-2 in China. So, in this context, let us see about inhaled vaccines. See, the inhaled vaccines that is currently in the news is developed by a China-based company called Canxino. Few months back, the nasal vaccine was in use and we have covered nasal vaccine on our 7th September 2022 in the news paper analysis. Interested people, please go and check it out. So, now coming back, see, like the nasal vaccine, the inhaled vaccine is also a needle-free COVID-19 vaccine. That is, there is no need to inject both nasal and inhaled vaccines. But the procedure for administering the vaccine is different. The nasal vaccine is sprayed inside the nose, but in the case of inhaled vaccine, first a mist of the vaccine is created in a cup. After that, this mist is sucked in through the mouth. You can see this short clip to understand better. So, this is about the administration of the vaccine. Now, what are all the advantages of the inhaled vaccine? See, the first advantage is easy administration. For administering a needle, some medical expert is required, right? But since the inhaled vaccine is needle-free, it can be easily administered by a semi-skilled person. So, the inhaled vaccine can be easily incorporated in mass vaccination drives. Second is, painless. See, some people, especially kids, they have an aversion towards getting injections due to the pain associated with the process. But, the inhaled vaccine is totally painless. So, the inhaled vaccine may persuade people who don't like getting an injection to get vaccinated. This will increase vaccine coverage. Third advantage is effectiveness. See, COVID virus mainly enters our body through our mouth and nose. So, if there is an effective immune response in our mucus layer of nose and mouth, the COVID virus can be neutralized before it reaches our body. It is based on this principle that the inhaled vaccine climbs its effectiveness. The inhaled vaccine helps mainly to give a boost to the immune cells that are present in the mucus membranes of the nose and mouth. Due to this, the COVID virus is neutralized at the point of entry itself. So, they are more effective. Now, the fourth advantage is they are better than the nasal vaccine. See, nasal vaccine are sprayed in the nose. So, it induces immune response mainly in the nasal passage. But, the inhaled vaccine is sucked through the mouth. So, the vaccine droplets are delivered deep in the airway. Due to this, the inhaled vaccine can induce a broader immune response than nasal vaccine. So, that is all you have to know about this inhaled vaccine. I hope we have covered in detail about inhaled vaccine. Currently in India, it is not approved for usage. But, in main sansa writing, you can use these points as a way forward. So, these learned points, now let us move to the next news article discussion. Now, look at this FAQ article. It speaks about the status of remote voting for non-resident Indians. So, in this context, let us learn about some of the points given in the news article. Before that, the syllabus relevant to this news article is highlighted here for your reference. Just go through it. Firstly, let us see why this is currently in talk. See, recently the Supreme Court had disposed of a batch of petitions which are seeking remote voting for NRAs. Now, this happened because the central government had told the court that it was looking for possible ways to facilitate remote voting for NRAs. Know that by keeping the voting rights of NRA in mind, earlier the central government had introduced a bill in 2017. This bill was proposed to facilitate proxy voting by overseas electors. However, this bill was lapsed and now the central government have told the Supreme Court that it is looking for various other options. That is why remote voting for NRAs is in news. See, we know that India has the largest diaspora population with nearly 1.35 crore NRAs spread across the globe right and many of them are in the Gulf countries, the USA and the UK. But the issue here is in the 2014 parliamentary elections only 11,846 NRAs registered and in that only a faction had voted in the election. So, here what is the reason for low NRA registration on voting? See, earlier the representation of people at barred the voting right of NRAs who stayed beyond 6 months in abroad. But what the government did was in 2010 it amended the RPA Act and this enabled the eligible NRAs who had stayed abroad beyond 6 months also to vote in the election. But unfortunately they have to visit the polling booth in person to vote and exercise their voting rights. But the issue here is this step did not encourage the NRAs to participate in voting because most of them are laborers. They lack financial resources to afford the travel tickets and there are also many other constraints. So, these are all the reasons why there is low NRA registration on voting. Now, let us see what the government did so far regarding remote voting for NRAs. See, between 2013 and 2014 many persons have filed a petition in the Supreme Court. Those petitions challenged the provision of the 2010 amendment which requires NRAs to visit the polling booth for voting in person. Then, the Supreme Court directed the government to take action. So, the Election Commission of India formed a committee in 2014 as per the Supreme Court's direction. See, this committee was formed to explore the voting options for overseas electors. The committee had recommended two remote voting options that is E postal ballot and proxy voting. So, what are these proxy voting and E postal ballot? Firstly, let us see about proxy voting. See, proxy voting is a voting process which allows a registered elector to delegate his voting rights to a particular representative, where the representative here is called a proxy. Note that the proxy is selected by the registered elector. So, proxy voting helps the person to exercise his or her voting rights through his or her proxy. Now, let us see about the E postal ballot. See, E postal ballot is the facility of casting votes by an elector using an electric voting system from a place other than the venue of his election booth. For this, we will take the example of electronically transmitted posted ballot system, ETPBS. Here, the voting ballot will be transmitted through electronic means to the voters and it enables the voters to cast their vote electronically. So, now let us see the process involved in ETPBS. Firstly, the NRA voters, they needed to make an application to the returning officer of his or her constituency. Here, the application will be given in person or sent through online. Then, the returning officer will verify the details and will send the ballot electronically to the voters. Next, the voters can register their mandate on the ballot printout and send it back to the returning officer with an attester declaration. Here, the NRA voter will either send the ballot by ordinary post or drop it at an Indian embassy where the embassy will post it to the concerned authority. So, this is about the process of ETPBS. See, we have discussed elaborately about electronically transmitted posted ballot system in our Hindi newspaper analysis dated 4th November 2022. That is yesterday, you can go and watch it. Now, coming back, know that the recommendation of the committee regarding remote voting is not yet implemented by the government. Also, here you have to note another thing, both ETPBS and proxy voting are currently available only to the service voters like those who are serving in the armed forces inside and outside India and those who are serving in diplomatic missions abroad. Then subsequently, ECI consulted the political parties about the implementation of proxy voting but the majority of the political parties were against proxy voting because the party said there is no guarantee that the proxy would vote as per the actual voter's choice. Then, in 2017, the central government introduced a bill to amend the Representation of People Act to remove the condition of in-person voting for NRAs and enable them to vote through proxies. The bill was passed in the Lok Sabha in 2018 but it never introduced in the Rajesh Sabha. So, the bill eventually lapsed with the dissolution of the 16th Lok Sabha. Then, in 2020, the ECI said to the law ministry that it was technically and administratively ready to facilitate ETPBS for NRAs in the 2021 Assembly election in five states. But the external AFI's ministry said it was not viable to roll out the ETPBS plan because there were huge logistical challenges relating to identity verification of voters, absence of polling agents, the polling on embassy staff, etc. So, this plan was also dropped. So, this is about the government's actions so far in facilitating remote voting for NRAs. Now, what about the current situation? This is a question, right? See, as we discussed earlier, the government has made assurance in the Supreme Court that it is looking for possible ways to facilitate remote voting for NRAs and will bring some positive note. Also, the law ministry in last March said that the government was exploring the possibility of allowing online voting for NRAs. Then, in April, the election commission said that ETPBS for NRAs was being considered and the action would be taken to implement the remote voting option. So, we have to wait and see what is going to happen in the future. I hope this news article discussion gave you an idea about the constraints for NRAs in exercising their voting rights. So, these learnt points. Now, let us move on to the next news article discussion. Now, have a look at this news article. See, this news article depicts an image of edible art. Yes, here in this image, you can see that a paddy field is turned into canvas and using the popular Japanese art form of rice paddy art or tambo art, a huge image of Jesus Christ is created. See, this is not something happening yesterday. Even few days back, a vyanad farmer created a shokha chakra using tambo art. So, what is this tambo art? How it is created and why it is gaining attention in India? That is what we are going to investigate in this news article discussion. See, in Japanese, rice field are called ta or tambo and as I already said, tambo art uses rice fields as a canvas to create huge design works by planting rice with different coloured leaves and grain heads. The idea is that the design illustration will be viewed from a high point like a viewing platform. Okay? Now, the image that you are looking at is created by Mr. Prasid Kumar Thail. He is a progressive farmer in Vayanadistic in Northern Kerala. He has used six varieties of rice seeds like Ramli, Dabarshala, Nazarbath, Ratthasali, Krishnakamout and Kalyani Violet to create a 3D image following this tambo art. So, how these gained pieces of tambo art are created? See, firstly, a design is chosen by the farmer to cultivate the rice seedlings. Remember, the artwork cannot be completed unless the rice plants are cultivated well. Nurturing the seedlings is an extremely important task. Along with the seedlings in the nursery, preparations also begin on the rice fields. Water is run into the fields, the earth is filtered and fertilizer is spread. Next, a base drawing of the design is made and a surveyor makes a design blueprint for the stakeout based on this. The area is then surveyed according to the coordinates written on the design blueprint and the field is staked out with the stakes joining together by ropes. Then, the farmer decides the variety of seedlings to be planted in each section. Next, the rice fields are finally planted. So, this is how the huge edible art is created. Now, since rice is the stable food of Japanese people, after the rice plants are harvested, the rice is milled into polished rice and later on it will be given out to those who participated in the event and it is used as a treat for lunch at that event. Okay? So, this is how the popular Japanese art form of rice paddy art is created. Now, coming back, see, this huge image was drawn by artist E.D. Raji with the assistance of only 8 umat workers. The young farmer spent 15,000 rupees to complete the paddy art work and since Tambo art are created with great attention paid to details, it is creating large tourist centers and the young farmer is expecting at least 10,000 visitors to his farm this year. On the other hand, the farmer's gene bank has also collected as many as 300 varieties of rice seeds from across the country of which 100 varieties have been cultivated this season on his 10 acres using organic methods. Now, seeing this, many other farmers in the district are also following his path in creating small images in their paddy fields as well. So, this is all you have to know about this news article. It is a kind of creative cultivation, right? So, knowing something new is also important. So, in this news article discussion, we saw in detail about the popular Japanese art form of rice paddy art or the Tambo art. So, these learned points. Now, let us move on to the next part of the news article discussion which is the preliminary practice question discussion. Now, look at this first question. This question is a previous year question which is asked in 2017. Let me read out the question for you. See, understand the question well so that you can answer the question correctly. The question says, at one of the places in India, if you stand on the seashore and watch the sea, you will find that the seawater resides from the shoreline a few kilometers and come back to the shore twice a day and you can actually walk on the seafloor when the water resides. This unique phenomenon is seen at option A, Bhavnagar, option B, Bhimuni Patnam, option C, Chandipur and option D, Naha Patnam. See, the correct answer for the question is option C, Chandipur. See, Chandipur is located in Odisha. It is also called as the hide-and-seek beach because during low tide, seawater in the Chandipur beach retreat inside the sea from 1 kilometer to 5 kilometer and it again comes back to the shore slowly during high tide. This happens twice every day and the famous Abdul Kalam Island where the integrated this range is located 70 kilometers south of Chandipur beach. So, the correct answer for this question is option C. Now, moving on, this question is regarding mRNA vaccine. Look at this first statement, in case of mRNA vaccine, our body is tricked into producing viral protein. This viral protein initiates immune response. Whether this statement is correct? See, this statement is actually correct. Unlike classical vaccine that use weakened or dead microbes to initiate immune response, the mRNA vaccine tricks our body into producing viral protein that generate immune response. So, this statement is actually correct. Now, look at the second statement, mRNA vaccine or completely synthetic and inexpensive to produce. See, this statement is also correct. They are inexpensive to produce compared to classical vaccine. Hence, they can be employed in mass vaccination drives. Now, look at this third statement, mRNA is considered safe than normal vaccines as they do not contain weaker or dead disease causing organism. Statement three is also correct, mRNA is safer than classical vaccine. Now, look at this statement four, mRNA vaccines effectiveness is lower when compared to classical vaccine. See, this statement is actually incorrect. They are more effective than classical vaccines. This is because mRNA vaccine help produce viral protein that generate immune response. So, here the correct answer for the question is option A, 1, 2 and 3 only because fourth statement is incorrect. Now, moving on, this question is about enforcement direct rate. Statement one, it says that it is a specialized financial investigation agency functions under the Ministry of Home Affairs. This statement is actually wrong, it comes under Department of Revenue of Ministry of Finance. So, this statement is incorrect. Now, look at the second statement, it is responsible for enforcing the provisions of prevention of money laundering act 2002. See, this we saw in our discussion itself, this statement is actually correct. It is a multi-disciplinary organization mandated with the task of enforcing the provisions of PMLA and FEMI. Now, the third statement states that it is headquartered at Mumbai. See, this statement is wrong. We saw that in the discussion itself, it is headquartered at New Delhi. It has a regional office in Mumbai, but not the head office. So, here the question asked for incorrect statement, the correct answer for the question is option C, 1 and 3 only because statement two is correct. Now, moving on, this question about glacier is a quiz question for you today. Just try to solve the question and post the correct answer in the comment section. So, the question displayed here is the mains practice question for you today. Just go through the question, write an answer and post it in the comment section. With this, we came to the end of the news article discussion. If you like the video, hit like, do comment and don't forget to subscribe to Shankara AS Academy YouTube channel. Thank you for listening.


Today we have with us Chris Kumar Ram Raju. So he will be presenting a talk on type check Django app. So over to you Chris Kumar now. Thank you. Thanks Kajetana. Good afternoon everyone. Welcome to my talk type check Django app. I can't who doesn't know T1. I hope you're all having a good time. Who am I? I'm Chris Kumar. I'm a software engineer based out of Bangalore. And I've been a volunteer to PyCon in the previous editions. I work for this company AdBase. So AdBase is a single platform to manage all your company specs. If in case you are interested, we are looking for developers. You can talk to me offline. For throughout the stock, I will be using Python 3.5 plus syntax. And whenever I say the static type checker, I mean mypy. And there are other static type checker available. But all of the code example and the concepts are very much tailored to the standard mypy. And by default Django version I'm using will be 3.2. And Django does not support Python type in stativity. So we will be using a third party plugin called Django stuffs. Types at runtime. Python is a dynamically type language and you don't need to give any type information to the interpreter. It can figure out all the type information and more details about the objects and it attributes everything at runtime. But there are some places where you need to know the types of an object. For that you have an inbuilt function called type. So type takes an argument and returns a value of the data and expression which is passed on as an argument. So here is an example type. You pass a tuple to it. It returns output as a tuple. It returns a concept if you apply to a Django user object.  What it does it outputs query.query set. So review available mypy checker. Sorry about that. Type is a double during. This will be a runtime and double during. Particle type. There is a tuple and stuff. And returns elements in that. This is rather static type. So mypy by default work type will be also interested in the every element inside. So here is an example of a reveal type where you pass a result of a Django user objects filter. Now you can see what the function is returning. It returns a user manager of user. This is a bug in Django stuff. It should be Django user query set of user. So mypy config. Since mypy is a third party library we install using a pip module. Now we need to configure mypy to work for Django source code. The first thing as I said Django does not come with default type annotation for all the code. It is annotated in a third party plugin called Django stuffs. So now we need to tell the mypy to load that plugin to look for all the types which are related to Django code. So how do we do that? In mypy.ini configuration file you have a section called plugins. In that you can mention what is the entry point for this particular Django stuffs module. Here we say mypy Django underscore plugin dot main. That is the entry point for this plugin. And then next we need to pass some configuration settings to this plugin because Django app pretty much works exclusively from starting from the setting. So you need to specify the settings location. In our case if your app name is say book counter you will specify book counter dot settings in the mypy file. So mypy internally will pass the settings variable to the plugin and the plugin will work as expected and return the types of all the Django objects and all the custom function return values. So what are those annotation syntax? So Python added type annotation in 3.5 onwards and you can annotate your variables, functions and classes wherever there is a data holder. And this is completely optional. There is not mandatory at all. So what are the syntax? In Python to assign a value user variable name and equal to value. So there is only one little bit of change that is like after declaring the name that is language colon str which denotes what is the type of the value. And this type can be like any type. It can be a inbuilt type or user defined type or composite types. For an example, second one is a very specific date type. Here date is a class. So it's going to be instance of date. That is what it means. Your colon date means your variable will hold instance of date. Now let's go to the next example. Some function takes a two arguments and returns a value. So the syntax is similar. It has got two arguments, both are soft type integers. So you specify the types as A colon int, B colon int and return value as int. So function can return more than one value. You put a square bracket and say like what is the type of first return type, what is the type of second return. Next let's go to the class. Here is initializer which has got three arguments. Name, age and isalite. Self is self-externatory because we know it is going to be instance of person. There is no need to annotate it. And we annotate the next three arguments that is name, age and isalive attribute. So annotating Django code. And let's start with a simple view function. And we'll see how to annotate. Then we'll move on to models. So here is a simple view function. So view function takes in a request and returns a response. So how do we annotate the input arguments? The request is a HTTP request. So we import it from Django to HTTP. And we say the return type HTTP response. So HTTP response is a proper super class of all the specialized responses like JSON response. So all the function will take an HTTP request. Sometimes it will take more than one argument. In this case it takes only one argument request and it returns a response. It's a type HTTP response. Here is another example. Here we have a function called view 404. The input is a HTTP request. But the response if you see in three examples, the response type is annotated in slightly different way. If you look at the body of this function, it returns one to one HTTP response not found. But these three are valid annotations which are accepted by my point. So let's try to see why these three return types are valid. So before getting into that, let's see what are the return types it is saying. First one it is a HTTP response not found. It is very clear to us its instance of HTTP response not found. So it is okay that HTTP response not found should be a correct one. Second one says like HTTP response is a return type. MyPy does not comply. Third one it says object. Now let's see why is this three, why is there three ways to annotate the function in two different ways. Python has this concept called method resolution or class. Method resolution or order is a way to specify, it is a way to know what is the inherited chain of a class. So it starts from a child class to the parent class to a child class. For example, if you see the HTTP response dot MRO, find every class you will have this method called MRO. When you call that MRO, it returns all the classes in the child class to parent class order. So the HTTP response is inherited in this order. HTTP response inherits HTTP response base. HTTP response base inherits object. If you see this MRO for HTTP response not found, it inherits the HTTP response. HTTP response internally inherits HTTP response base. and internally inherits objects. So this is the reason that PyPy did not complain even though the return type of HTTP response not found. Even when the source code of the function was annotated to retain HTTP response base or object, it did not complain at all. So this is basically an alignment with a concept called LISCOP substitution principle. So what LISCOP substitution principle states is that in an object oriented program substituting a superclass object reference with an object of any of its subclass, the program should not break. Since HTTP response not found is a special type of HTTP response, it did not complain that these classes are two different types. That is the reason why MyPy accepted the type annotation. Next is Django models. Now let's see a simple create scenario. Here is a simple model question which takes in two explicit model fields. Model question text is of character field. Update is of datetime field. We have a function create question which takes in a question string and returns a question. It is a simple way to create a Django model and return. Since it is returning instance of question, we will annotate the return type as a class name which indicates it is going to return an instance of this particular class. Now let's do a read function. We have a simple function called get question which takes in a question text which is of type string and returns a question. And internally it uses filter method. So if the question matches the question in the database, it will be very first instance of the question. When you run this code against MyPy, MyPy complains with one error. The error message is incompatible return value type optional of any expected questions. Let's take a look at how objects.filter works. Object.filter is nothing but a var query where whenever the result is found, it returns all the results. Since we are using dot first on it, it will return a question only when there is a match. If there is no match, it will return none. MyPy was exactly able to identify this and it says optional. Optional means none. Any means are any instance which it returns since object manager can return anything. Here it is very specific to question. What it is saying is that get question is annotated to return question, but the source code or the return statement can return a none or question. Now this is very fundamental difference with how the dynamic behavior and static typing works. If you see how can we solve this problem, MyPy already said that it can return optional of question. So what we will do will import optional from typing module. And then you can say the return type of this function as optional of question. Optional, the square brackets means of what is the type it will return. Optional means it can return none or question. So all the helper methods and attributes or the references for typing is available in typing module. This is one way to solve this problem. There is another way to solve this problem using MyPy config. So start something called a strict underscore option. Strict underscore optional is a configuration parameter in this configurational file where you can set that value to false. Then what it will do is whenever a function returns a none or an object, MyPy will not complain that your function does not reflect that. For example, in our case, if we return this as a question, annotate it as a question and even though we didn't specify this optional of question, MyPy will not complain. So this is a very good trade-off between a linear code type checker and a strict type checker because depending on your source code and the level of the maturity of your source code, you can decide to use one of the modes to start with type checking. You can start with a linear mode like strict optional is equal to false. There are various other options. Once your code means to use a very good maturity and you have a lot of type coverage, then you can go back to strict underscore optional and then set it to true. You get the maximum mileage out of MyPy for strict mode configurations. So next is a filter method. The filter method is available on the object manager.objects. So when you do objects.filter, Django returns a query set and the query set contains a model instances inside it. You can consider it like a list of values. So all the values inside the query set will be of the homogeneous type. That is, if you are using a user.objects.filter, all the items inside it are going to be user objects. Or if you are going to use a group object, all the items inside the query set is going to be group. This is important how you will be accessed Django overall. So here is some example. How do you annotate a function which returns a query set? Similar to optional of question, we say query set of question, which means the return type is going to be a query set. That is outer type and the inner type is going, inner type which will contain will be the instance of question. You can consider it like a box model where like a box is a query set. Items inside there are the model instances. In our case, it is going to be question. Some of the other methods which returns query set in Django or more like all, reverse, order by, and union. There are a couple of other methods on object manager which returns query set. Next we will see an aggregate function. Aggregate function is a way to compress the data in a database or in a table to return a very few values. For example, average is one such example. To illustrate the use case, I have two models. The first model is a publisher model with one explicit field name of character field. Second one is book model with five explicit fields, six explicit fields and name of character field, pages of integer field, prices of decimal field. Rating is a float field. Publisher is a foreign key to publisher model and publish date is a publish date field. So here is an get average function. What it does is like in the books model it tries to give the average price of all the books in that particular table. Since it is compressing or summarizing the data, it will return only one value. So now AVG underscore price is equal to average. So AVG is a keyword here. So when the return, when this function returns a value, returns a value as a dictionary where key is the query expression that is AVG underscore price, value is the type of the field of the field price. So in our model declaration, the prices of decimal field ends the compress to value or the summarized value is a decimal value. Now let's try to annotate this particular function. Since we know the return type is a dictionary, we can say the return type is a dictionary, but we need to annotate what is the type of the key and what is the type of the value. Key is going to be average underscore price and the value is going to be decimal. So we will annotate it as string comma decimal. Always the type of key goes in the first and followed by a comma and then the value of the type is annotated. Next let's see the annotate method. So jango annotate method is nothing but a group by query. You group by items in a table by a particular column and you either do some sort of aggregate function like count star or average of all this. So in our case we have already a publisher model. What we will do is we will try to find number of books published by each publisher. So what we do we are going to do a we are going to use annotate method. So publisher.objects.annotate I am going to take a sip of water. So publisher.objects.annotate it is going to annotate all the books published by a particular publisher by name and print the number of books. So if you see the output of this function it is going to return more than one value because there are more than one publisher in the there are more than one publisher in the database. So you can see the values. It looks like a list of dictionaries since we are using a list comprehension that is why it is represented on this. So it is going to contain a name and number of books by each publisher and there are two publishers. So we have two rows in the result. Now returning a query set so now we are slightly modified the count by publisher function rather than annotating or returning all the values of the num books everything. We just make sure it returns a query set and top of that we have one more function called printpub which takes an argument num books and prints the number of books which are greater than specified value only those publisher details else it prints all the publisher details. So let's have a look at the printpub function. Let's got an if condition and then a for loop. If condition has got if it is greater than zero the num books is greater than zero then we filter the publishers were published more than the past in value and then we store the result in a result variable same thing in the else case we are not doing any filter and once we have the result we iterate over the results and we print the name and the number of books published by each publisher. So the output will look something like this so pen going to and vintage one. So this is not a dictionary now let's try to annotate this particular function. So count by publisher we know it returns more than one value we will annotate it as an iterable of published book in the previous example you saw like it looked like a dictionary it had two attributes. So what I will do was I will do create a class called published book which inherits from the type of dict so type dict is a super class of dict what it does is like whenever you know keys of a dictionary and values which is of a static dictionary you can consider we know that dictionary will contain only two keys and we know what is the name what is the type so what we do is we create a new class called published book count the key value is name and the value against that key is going to be string num books is the key and integer is going to be the the value contained in that dictionary item. Now we annotate iterable of published book count that means like we are going to have some kind of a iterable container where you can put a form and each item is going to represent published book count. Once you run this against MyPy, MyPy complains there are two set of errors. The first one it says is like it got very set of any expected iterable of published book count. So what MyPy is saying is that you have annotated the function to return annotation says it's a iterable of published book count but it has from the source code since annotate method returns a query set MyPy is complaining that this function count by publisher is returning a query set of any but not of iterable of published book count that is quite understandable. What is the second error? Second error is building upon the very first error the iterable of published book count has no attribute filter. So what it is saying is like in the for loop not in the for loop in if block filter condition which further filters the result. So it says like the iterable does not have a method called filter but we are accessing the object with a filter method. So MyPy caught these two errors. Now let's see the validity of this error. Whatever MyPy is complaining seems to be legit. Let's see how we can fix these two errors. The first is since MyPy is saying the return type of code by publisher is going to be a query set. Let's change the orientation of this function from an iterable of published book count to a query set of publisher. And then let's run this MyPy. When you do that MyPy now complies with only one error. The first error is gone. That's a second error. Now what it is saying is the publisher model has no attribute numbooks. This is coming from the for statement where we are iterating over the result and printing each rows values. Now it is saying the publisher model had only one field. One attribute called name but there is no attribute called numbooks. If you work with Django for so far you would understand the code what we wrote is legit. Because numbooks is a attribute field which is inserted on the fly by Django or but we don't have to declare that field in Django models. So it is a very legit code properly if you run a test case it will pass, if you run it in the production it will work. But MyPy being a static type checker it does not understand the dynamic behavior of Django because Django is inserting this attribute num underscore books at run time at Python run time. So now MyPy is unable to understand this magic. MyPy complies that there is no attribute called num underscore books which is not declared in publishing. So right now this is causing MyPy confusion. How do we fix this? So this is actually a bug in Django Stubbs project but there is a solution for us. At the time of preparing the slides there was a bug right now this bug is fixed but if you are using some older version of Django Stubbs project you will encounter the same bug. There is a solution for this. How we do this? There is a bug condition you can use it. So from typing module you can import something called type checking. This type checking is a Boolean flag. If you put if type checking this particular piece of code will be only executed inside MyPy. So when you try to run this code in using Python interpreter what would happen is that if block will not be executed at all. Since we know certain portions can be executed only by MyPy what we will do is we will say type checking if type and what we will do is we will create a new class called type publisher which in heads of publisher and we will add a new attribute called num underscore books is our field integer field. Now what is happening? Now we are creating a new model which has got name and num books. Now we will add a meta configuration called abstract is equal to 2. Now we will change the annotation to query set of type publisher and now when we run this code with MyPy MyPy will not complain at all. This is because right now the during type annotation type MyPy sees the type publisher it sees two attributes name and num books which satisfy all the condition and it goes through some of the tools so that if you are starting to annotate a Django project it can become very hard to annotate a large piece of code so what we can do is there is a tool called PyAnnotate. PyAnnotate is a tool which can infer the types of Django object during runtime and convert it to MyPy types. You can use a PyTest plugin called PyTest Annotate where you can run this Python source code and infer the types during test time and then use it to annotate those existing source code. Here is a function which we saw earlier that's got no type information. Now what you do is you write some test cases for that particular function which invokes all the code you wanted to annotate and then what you do is you run Django settings module like this. So I'm using Poetry you pass an extra options called annotate output. It will store all the outputs in annotation.json file and the output looks something like this. You have the path, what is the function name, what is the type annotation of the function infer during runtime and then what you can do is you can apply the changes once the test case is done you can say annotate this particular file that is view.py file from this annotation file of Python 3 syntax this is quite useful too. It will help you to get some kind of coverage from 0 to some expose. This is how the code looks. The code looks legit it can handle imports but there will be some changes definitely required from your end after seeing the coverage and the last part of this presentation is learning resource. I come up with a project called Python typing k-ons. Python typing k-ons is an interactive way to learn Python type annotation. To learn all the concepts and gradual typing in Python you need the Python code with the proper structure. This git repository has classified all the code into three sections, Python, Django and DRF you can run each file using this command line option and it will print out all the errors in mypy and as a learner you open the source code and you look into what is the error and try to modify the type hints or add the missing type and then you run the code. You reduce the errors from 5 to 3 from 3 to 1. At the end of this once you solve this problem you will understand how that particular concept works in mypy and thank you in case you have any doubts I'm happy to take the question. These are my contact details. Thank you Chris Kumar for the wonderful talk on type checking so we have some questions from the audience. So the first question is how do you decide whether or not you should add type checking in a Django app That's a good question like if you say like that the camp for type hints in Python is divided into two territories people say I don't want type hints people say I want type hints. My view in this is is your source code large? When you say large it is like you have like 5-6 apps you have some 40-50 Django models and it is growing every day it is going 1. 2. How long this project will be active? Is it going to be active for what to say like next 2 years, 3 years? 3. Is it just a pet project or not? 4. Is there more collaborators? So in my opinion if your project is going to last longer and if there is going to be more collaborators I have seen that's a lot of value for type hints in Python because it helps you to catch a lot of bugs before even writing test cases which I find to be useful and also it helps in navigating a larger piece code base and it also improves the readability but if you are only 1% writing on a small project then you can decide not to use it because there is a lot of overhead in adding type hints as well so you have to see what is that trade-off and when to add type hints to a project Thank you. So let me check whether we have any additional question here okay there is one more question you can take up so the second question is what's the standard way to annotate Pandas data frames so I use pandas.dataframe haven't checked with my pie so as I said earlier like Pandas by default does not support type hints when I said by default means in the source code when they write Pandas library there is very less support for what to say Pandas.dataframe what is that type so there are third-party libraries which maintain steps for what to say for NumPy for scikit-learn for data what to say for Pandas so you have to use one of those third-party libraries as a plugin how I showed for Django and you can start annotating your data frame using those libraries and it will help you to get to a decent level I cannot guarantee that all of the features in Pandas or all of the Pandas source code you will be able to annotate using those libraries but it is catching up and as I said it is not even complete in standard library itself


More than 300 years ago, the first pioneers crossed the oceans to a new world. A promise called the promise of a land where a man could build his own house, farm his own acres, raise his children in freedom. They carved from the wilderness an empire of agriculture and industry. They set for themselves new and higher standards of living. And yet, in one of the great river valleys of America, something went wrong. In the Tennessee Valley, three centuries later, the descendants of the pioneers were neglected people, living in a ruined land. For these children, the hope and the promise were dead. Even the older men had forgotten that the valley had once been bright with promise and with hope. Horace Higgins was one of the many who had given up the fight. What's the use, he said? You fill up those gullies and the first rain washes it away. It's the same with all the land around here. It may have been good land once, but it's bad land now. Bad land. Hopeless land. Henry Clark wondered. Erosion, the scientists call it, the eating away of the soil. A destruction which began innocently when the early settlers cut down the forests. When the farmers, out of ignorance, plowed straight furrows down the hillside. Destruction from the sky. This is the way it was, year after year, in a forgotten part of the United States. This was the havoc caused by greed and neglect and men working alone and unaided against the forces of nature. Farm, towns, industries, smash, hundreds drown, thousands made homeless. The energies of the river running to waste. The energies of the people too. Henry Clark's trouble was the trouble of three million Americans in the Tennessee Valley. It became the direct concern of 130 million Americans in the 48 states. A challenge to democracy and its ability to care for its own. The valley of the Tennessee River lies in the southeastern United States. It covers an area of 40,000 square miles, nearly as large as England. It was a problem of reconstruction. Reconstruction of land. Reconstruction of people. Democracy met the test. It found the men to supervise the job. James P. Pope, United States Senator from the West. Harcourt Morgan, president of the University of Tennessee, who had worked out an agricultural program for the whole area. David Lillianthal, administrator and champion of legislation for cooperative electric power. George Norris, the great American statesman, who long had dreamed of regional planning, of setting up a national experiment in one region which could serve as a yardstick for every region. This was the plan. To chain the river through a series of giant dams, checking the floods, to open it to navigation from its mouth to its headwater. To give the farmers the benefit of modern science and research. To help them control the water on their land and restore the fertility of the soil. To reforest millions of acres on the ravaged hillsides. To exploit the mineral resources of the area. To use the electric power generated by the dams to develop and rehabilitate industry in the cities. To electrify the farms through rural cooperatives. Above all, to prove that human problems can be solved by reason, science and education. The Tennessee Valley was to be pioneered again. This time to be developed, not plundered. This time not for the benefit of a few, but for the many who lived in it. These were the new pioneers, the architects, the research chemists, the agricultural experts, the power men, the designers of hydroelectric dams. Their method was to control nature not by defying her as in the wasteful past, but by understanding her and harnessing her in the service of humanity. In May 1933, a new chapter was written in American public policy when the plan was brought before the representatives of the people in Congress. An act was passed creating the TVA, the Tennessee Valley Authority. President Roosevelt told the nation that the project was to be developed in the United States. The project was to be developed President Roosevelt told the nation that the project would set an example of planning not for this generation alone, but for all the generations to come. Then things began to happen in the valley. To many of the valley people, the plan was an intrusion. They said, let the government men do things with machines over the mountains. None of our business. But youth was more inquisitive and the pioneer spirit was still alive. Over the mountain was something new, big, exciting. Music The damn builders 200,000 of them in all 4,000 on this one project. Valley farmers and miners, mountaineers and city workers. To them, this was more than a job. They had a stake in what they were doing. They were building for themselves and for their children, for the future of the valley. As the month passed, the farmers started coming to the dams to see for themselves. 1,000. 1,000. 1,000. 1,000. They were impressed by the magnitude of the work, but even the open-minded ones, like Henry Clark, couldn't understand at first just what it all had to do with them. It was the business of John Warden, the TVA agricultural representative, to answer that. It has everything to do with the farmers, he said. The dams are just the beginning. Without the fullest cooperation of the people on the land, they're worthless. Music There were small meetings up and down the valley. John Warden told the farmers, 10 inches of topsoil supports all the life on earth. Every drop of rain that falls on your fields carries away a bit of this soil. Every time it rains, the gullies, the scars on your fields, grow deeper and wider. Every year the precious topsoil goes faster. The undersoil is hard and sterile. The water which should have soaked into your land runs off, uselessly. Your topsoil travels with it, uselessly, down to the delta of the river. Millions of tons of good farming soil, lost forever, blowing away with the wind. All this waste isn't necessary. It can be stopped. Your land can be saved if we work together. You've seen the dams, but they're only part of the plan. The rest of it is up to you. If we're to succeed, all of us, you must learn to stop the erosion of your own land. The TVA was created for you to teach you new methods to provide you with fertilizers to restore your soil. The land is yours, the dams are yours, the whole TVA is yours. We want you to use it. This is how you can become a part of the plan. We need volunteers to try out the new methods to prove that they are the right ones. Thousands of farmers have already volunteered. How about you? It isn't easy for men bound by habit and tradition to change their whole way of thinking. John Warden knew the farmers of the isolated back valleys. He had talked to hundreds of groups like this, and he knew they needed time. In signing with the TVA, Henry Clark became what was called a test demonstration farmer. His farm and thousands of others were to serve as laboratories where the new methods could be tested and observed by all. Using a terracer made available by the TVA, John Warden showed Henry the principles of contour farming. This was a radical departure from the old method of square farm. Flowing by contour, Henry learned to follow the curve of the land. No longer could the water run down straight ferns, the curves held it on the land. Then, to put life into the exhausted soil, Henry used a new phosphate fertilizer developed by the chemists from ore found in the region. The first season, Henry's cheap crop was clover. This was to provide the soil with nitrogen and revitalize the land. But it wasn't the cash crop. Henry had been warned. Still, when he made up his accounts at the end of the year, he couldn't help but feel, well, he sort of set his heart on that new tract. This was the crucial period, the first season. The TVA men had known it would be. They were sure of their equipment and methods. The human minds and emotions were another thing. It was a hard decision for Henry Clark, whether he should go on. But he was the descendant of pioneers, of men who had taken a chance, and who had known that their salvation lay in cooperation. The old spirit of the pioneers was reawakened. The dam builders, farmers, the machines began to work as one. By the next year, there were results. Henry Clark had the best crop of tobacco ever grown in the county. He was sending substantial quantities of food to market, and giving his neighbors plenty of food for thought. They came to see the new fertilizer, the new methods, and the student became a teacher. In the Tennessee Valley that year, 30,000 other demonstration farmers became teachers, too. For the next year's harvest, Henry and his neighbors had a threshing machine, especially designed by the TVA experts for this valley. Each group of farmers had a machine. Each farmer had an equal right to its youth. No longer was it one man alone against the drought and the flood. For the first time they were acting together, cooperatively, for a common purpose. And even more important, a change was beginning to come into their thinking. For the first time they were thinking in terms of each other, what they could accomplish together by working together. With new machinery, new methods, with a definite plan to follow, a plan that embraced them all, the farmers worked, and the land responded. When Hollis Higgins saw Henry riding his new tractor, he began to understand the real meaning of TVA, that the individual, through cooperation with his fellows, becomes a more important individual. As John Warden says, when you develop people, you have something permanent. The development of people is the first concern of a democracy. In school, the children learn how to use the things that were built for them. They learn how the dams work. Up in the mountains on the tributary streams, high dams back up reservoirs against the time of drought, releasing the water when it is needed, holding it in check when the rains come. Down the Tennessee River itself, wide dams control the water step by step. Instead of the alternate floods and droughts, water can now be dispatched, as trains are dispatched on a railroad system. Music These are the symbols of a nation's constructive energy. Douglas, Gontesville, Cherokee, Wilson, Pickwick Landing, Chickamauga, Iwasa, Montana, Hale's Bar, Watts Bar, Fort Lauderdale, Breland, Appalachia, Norris, built for and owned by the people of the United States. Music Day and night in peace and war, the dams work for the people. Power for the factories, power for new industries, power to run a million machines running out airfacts, practice, textiles, engines, shoes, fertilizers, aluminum, cheap and abundant power to light the cities and villages, power for the farmers, power that can be converted to a hundred homely uses, power working tirelessly, endlessly, raising standards, reducing drudgery, power in the hands of the people. Music The children of the Tennessee Valley have recaptured the hope of their grandfather. They have learned that the TVA is indeed a artist, a measure of what men can build in peace, a measure of the stature of a new and better world, a world with dignity, work and hope for all. A world a child can walk into. Music