Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 196

“Devsearch”

MAJOR PROJECT REPORT (KCA-451)

SUBMITTED TO

DR. A.P.J. ABDUL KALAM TECHNICAL UNIVERSITY, LUCKNOW


(U.P.)

FOR THE PARTIAL FULFILLMENT OF THE DEGREE OF MASTER

IN COMPUTER APPLICATION SESSION (2022-24)

Under the Guidance of Submitted by:

Prof. Mr. Shailender Vats Naina Sharma (2200980140026)


Assistant Professor Rohit Rajput (2200980140035)
School of Sudhanshu Vishwakarma (2200980140044)
IT IMS-Noida

INSTITUTE OF MANAGEMENT STUDIES, NOIDA


1. Roll No.: 2200980140026, 2200980140035, 2200980140044
2. Name of the student: Naina Sharma, Rohit Rajput, Sudhanshu Vishwakarma
3. E-mail:
nainasharma.mca22013@ imsnoida.com,
rohitrajput.mca22028@ imsnoida.com,
sudhanshuvishwakarma.mca22029@imsnoida.com
4. Mob. No.- 9354382169, 8860473773, 8853451387
5. Title of the Major Project: Devsearch
6. Name of the Guide: Mr. Shailender Vats

For Office Use Only:

Signature of the Mentor

Approved Not Approved Date:

Suggestions (if any):-

2
INDEX

S.No. Description Page No.


1. Project Profile
1.1 Project Definition
1.2 Project Description
1.3 Existing System / Work Environment
1.4 Problem Statements
1.5 Need for New System
1.6 Proposed System & Features
1.7 Scope
1.8 Outcomes
1.9 Tools & Technology Used
1.10 Project Plan
2. Requirement Analysis
2.1 Feasibility Study
2.2 Users of the System
2.3 Modules
2.4 Hardware & Software Requirements
3. Design
3.1 Diagrams
3.1.1 DFD
3.1.2 Entity Relationship Diagram
4. Implementation
4.1 Code
5. Testing
5.1 Test Strategy/Test Cases
6. Future Enhancement
7. Screenshot
8. Bibliography

3
ACKNOWLEDGEMENT

I am very grateful to my Major project (KCA-451) Mr. Shailender Vats, for


giving his valuable time and constructive guidance in preparing the
Report-Major Project (KCA-451). It would not have been possible to work
on this project without his kind encouragement and valuable guidance.

DATE: SIGNATURE:

4
CERTIFICATE OF ORIGINALITY

I hereby declare that the MCA Major Project (KCA-451) titled “Devsearch”
submitted to the IT Department, IMS Noida, which is affiliated with DR.
A.P.J. ABDUL KALAM TECHNICAL UNIVERSITY
LUCKNOW (U.P.) for the partial fulfillment of the degree of Masters of
Computer Application, in Session (2022-24). This has not previously
formed the basis for the award of any other degree, diploma, or other title
from any other University.

PLACE: IMS NOIDA

DATE:

SIGNATURE:

5
6
1.Project Profile

1.1 Project Definition

What is Devsearch?
Devsearch is a vast platform that changes how software developers work together on
projects. It’s more than just a place to store code; it offers tools for controlling versions,
tracking issues, and reviewing code, which are essential for creating software today.

Devsearch also has features like forks, pull requests, and merges that help
developers from all over the world work on open-source projects and other
collaborative efforts together.

Techopedia explains the Devsearch Meaning


Understanding Git is crucial for grasping the full Devsearch meaning, as it is the foundation of
Devsearch.

It’s a system that lets developers keep track of and manage changes in their code, allowing
many people to work on the same project at the same time without messing up each other’s
work. This system keeps a detailed record of all changes, so you can go back to earlier
versions if you need to.

Because Git can handle projects of any size efficiently and flexibly, it’s the go-to choice
for developers and is key to making Devsearch a place where people can work together
effectively.

7
1.2 Project Description
DevSearch is an innovative platform designed to streamline the process of
discovering, connecting, and collaborating with developers worldwide. With the
exponential growth of the tech industry, the demand for skilled developers has
never been higher. However, the challenge lies in finding the right talent for
specific projects or roles. DevSearch addresses this challenge by providing a
comprehensive solution that empowers both developers and employers.

At its core, DevSearch functions as a centralized hub where developers can


showcase their skills, projects, and expertise. Through detailed profiles,
developers can highlight their programming languages, frameworks, experience
levels, and previous projects. This allows employers to quickly assess a
developer's suitability for a particular role or project based on their skills and
experience.

One of the key features of DevSearch is its advanced search functionality.


Employers can utilize various filters to narrow down their search and find
developers who meet their specific criteria. Whether it's by programming
language, experience level, location, or project type, employers can easily find the
right talent for their needs.

In addition to traditional search functionality, DevSearch incorporates AI-powered


recommendation algorithms. These algorithms analyze the requirements of a
project or job posting and suggest developers who are the best fit based on their
skills, experience, and past collaborations. This proactive approach not only saves
time for employers but also helps them discover talented developers they may not
have found otherwise.

DevSearch also fosters collaboration and networking within the developer


community. Developers can connect with each other, share knowledge, and
collaborate on projects directly through the platform. This creates
opportunities for skill development, mentorship, and professional growth.

8
Furthermore, DevSearch offers a seamless hiring process, allowing employers to
manage job postings, applications, and interviews all within the platform. From
posting a job opening to extending an offer, employers can efficiently navigate
each step of the hiring process, saving time and resources.

Security and privacy are paramount on DevSearch. The platform employs robust
encryption protocols to safeguard sensitive information and ensure user privacy.
Developers have control over the visibility of their profiles and can choose to
share only relevant information with potential employers.

Overall, DevSearch revolutionizes the way developers are discovered, hired, and
connected within the tech industry. By providing a user-friendly platform with
powerful search and recommendation capabilities, DevSearch empowers both
developers and employers to find the perfect match for their projects and career
opportunities.

9
1.3 Existing System / Work Environment

1.3.1) Existing System:

The existing system of DevSearch comprises a user-friendly platform that


serves as a centralized hub for developers and employers to connect. It
offers features such as user profiles, advanced search functionality,
AI-powered recommendations, collaboration tools, and a streamlined hiring
process.

1. User Profiles: Developers create detailed profiles showcasing their skills,


experience, projects, and expertise. Employers can view these profiles to
assess a developer's suitability for specific roles or projects.

2. Advanced Search: Employers can utilize various filters to narrow down


their search for developers based on criteria such as programming language,
experience level, location, and project type. This helps them find the right
talent efficiently.

3. AI-Powered Recommendations: DevSearch employs recommendation


algorithms that analyze project requirements and suggest developers who
are the best fit based on their skills, experience, and past collaborations.
This proactive approach helps employers discover talented developers
quickly.

4. Collaboration Tools: Developers can connect with each other, share


knowledge, and collaborate on projects directly through the platform. This
fosters a sense of community and provides opportunities for skill
development and mentorship.

5. Streamlined Hiring Process: Employers can manage job postings,


applications, and interviews within the platform. From posting a job
opening to extending an offer, employers can efficiently navigate each step
of the hiring process.

10
6. Security and Privacy: DevSearch prioritizes security and privacy,
employing robust encryption protocols to safeguard sensitive information
and ensure user privacy. Developers have control over the visibility of their
profiles and can choose what information to share with potential employers.

Overall, the existing system of DevSearch provides a comprehensive


solution for discovering, connecting, and collaborating with developers
worldwide. Its user-friendly interface, advanced search capabilities,
AI-powered recommendations, collaboration tools, and streamlined hiring
process make it a valuable resource for both developers and employers in
the tech industry.

11
1.3.2) Work Environment

The work environment at DevSearch is characterized by innovation, collaboration,


and a passion for technology. Here's an overview of what it's like:

1. Innovative Culture: DevSearch fosters an environment that encourages


innovation and creativity. Team members are empowered to think outside the
box, experiment with new ideas, and find innovative solutions to challenges
in the tech industry.

2. Collaborative Atmosphere: Collaboration is at the heart of DevSearch's


work environment. Team members regularly collaborate on projects, share
knowledge and expertise, and support each other to achieve common goals.
Whether it's brainstorming new features, troubleshooting technical issues, or
working on marketing strategies, collaboration is key to success.

3. Tech-Focused: As a tech-driven company, DevSearch places a strong


emphasis on technology and keeps abreast of the latest advancements in
the field. Team members are passionate about technology and are
committed to leveraging it to create impactful solutions for developers and
employers.

4. Agile Methodology: DevSearch embraces agile methodologies in its


development processes. Teams work in sprints, allowing for flexibility,
adaptability, and continuous improvement. This approach enables the
company to respond quickly to changes in user needs and market trends.

5. Remote Work Culture: DevSearch embraces remote work culture,


providing flexibility for team members to work from anywhere. Remote work is
supported by robust communication and collaboration tools, ensuring that teams
can stay connected and productive regardless of their location.

6. Diverse and Inclusive: DevSearch values diversity and inclusion and


believes that diverse perspectives lead to better outcomes. The company is
committed to creating an inclusive work environment where all team members
feel valued, respected, and empowered to contribute their unique skills and
experiences.

12
7. Continuous Learning: DevSearch encourages continuous learning and
professional development. Team members have access to resources such
as online courses, workshops, and conferences to enhance their skills and
stay updated on industry trends.

Overall, the work environment at DevSearch is dynamic, collaborative, and


tech-focused, where team members are empowered to innovate, collaborate, and
grow professionally.

13
1.4 Problem Statements

The problem statement for DevSearch revolves around the challenges faced
by both developers and employers in the tech industry:

1. Finding the Right Talent:


Employers often struggle to find skilled developers who are the right fit for
their projects or job openings. The process of sourcing, screening, and hiring
talent can be time-consuming and inefficient.

2. Navigating a Fragmented Landscape:


The tech industry is vast and diverse, with developers specializing in
various programming languages, frameworks, and domains. Navigating this
fragmented landscape to find the perfect match for a project or role can be
daunting for employers.

3. Lack of Visibility for Developers:


Many talented developers struggle to gain visibility and showcase their
skills to potential employers. Without a platform to effectively showcase
their expertise, developers may miss out on valuable career opportunities.

4. Tedious Hiring Processes:


Traditional hiring processes can be cumbersome and involve multiple
rounds of interviews, assessments, and negotiations. This not only prolongs
the time to hire but also adds administrative overhead for both employers
and candidates.

5. Limited Networking Opportunities:


Developers may find it challenging to connect with like-minded
professionals, share knowledge, and collaborate on projects outside of their
immediate circles. This limits their ability to expand their network and
collaborate on diverse projects.

14
6. Privacy and Security Concerns:
Both developers and employers are concerned about the security and
privacy of their data when using online platforms for hiring and
networking. Ensuring the confidentiality of sensitive information is
paramount to
building trust in such platforms.

In summary, the problem statement for DevSearch revolves around the need for a
comprehensive solution that simplifies the process of discovering, connecting, and
collaborating with developers while addressing concerns related to talent sourcing,
networking, privacy, and security in the tech industry.

15
1.5 Need for New System

Absolutely, let's delve into each need of DevSearch in detail:

1. Efficient Talent Acquisition: DevSearch addresses the need for companies to


efficiently acquire talent by providing a platform where employers can easily
find skilled developers for their projects or teams. The platform streamlines the
talent acquisition process, saving time and resources for employers.

2. Comprehensive Developer Profiles: Developers need a platform to create


comprehensive profiles that showcase their skills, experience, and projects.
DevSearch allows developers to highlight their expertise effectively,
increasing their visibility to potential employers.

3. Tailored Job Matching: Employers seek a platform where they can find
developers whose skills align with their project requirements or job openings.
DevSearch facilitates tailored job matching by allowing employers to search for
developers based on specific criteria such as programming languages,
experience level, and location.

4. Advanced Search Capabilities: DevSearch offers advanced search filters


that enable employers to find developers with precision. Whether it's filtering by
programming language proficiency, years of experience, or project type, the
platform provides robust search functionality to meet employers' needs.

5. Proactive Talent Recommendations: DevSearch's recommendation


algorithms analyze project requirements and developer profiles to suggest suitable
candidates to employers. This proactive approach helps employers discover
talented developers they may not have found through traditional search methods.

6. Collaboration Tools: Developers require tools to connect, communicate,


and collaborate on projects with other developers. DevSearch provides
collaboration tools such as messaging, project sharing, and version control
integration to facilitate seamless teamwork.

16
7. Streamlined Hiring Process: DevSearch streamlines the hiring process by
providing tools for managing job postings, applications, and interviews within one
centralized platform. Employers can track candidate progress, schedule
interviews, and make hiring decisions efficiently.

8. Remote Work Support: With the increasing prevalence of remote


work, DevSearch supports remote collaboration by providing a platform
where developers can work from anywhere and collaborate effectively with
team members.

9. Continuous Learning Resources: DevSearch offers a wide range of resources


such as online courses, tutorials, and articles to support developers in their
continuous learning and skill development journey. Developers can stay updated
on the latest technologies and trends to enhance their expertise.

10. Networking Opportunities: DevSearch facilitates networking


opportunities for developers to connect with peers, mentors, and potential
collaborators within the tech community. Through forums, discussions, and
events, developers can expand their professional network and build valuable
relationships.

11. Privacy and Data Security: Both developers and employers require
assurance that their data is secure and their privacy is protected when using the
platform for hiring and networking. DevSearch prioritizes data security and
implements robust measures to safeguard user information.

12. Feedback and Review Mechanism: DevSearch incorporates a feedback


and review system where employers can provide feedback on developers they
have worked with, helping to build trust and credibility within the community.

13. Diverse Talent Pool: Employers value access to a diverse talent pool with
developers from different backgrounds, experiences, and perspectives.
DevSearch promotes diversity and inclusion, ensuring that employers have access
to a wide range of talented developers.

17
14. Community Engagement: DevSearch fosters a sense of community by
encouraging engagement through forums, discussions, and events within the
platform. Developers can exchange ideas, seek advice, and collaborate on
projects, creating a vibrant and supportive community.

15. Career Growth Opportunities: Developers seek opportunities for career


growth, advancement, and professional development. DevSearch provides
access to job openings, mentorship programs, and learning resources to help
developers achieve their career goals and aspirations.

18
1.6 Proposed System & Features

1.6.1) Proposed System:

The proposed system of DevSearch builds upon its existing features while
introducing enhancements to further streamline the process of discovering,
connecting, and collaborating with developers. Here's an outline of the proposed
system:

1. Enhanced User Profiles: Developers can create more comprehensive


profiles, including additional sections for certifications, awards, and testimonials
from previous employers or clients.
This allows developers to showcase their expertise and credibility more
effectively.

2. Improved Search Functionality: The search functionality is enhanced with


more advanced filters and sorting options, allowing employers to find
developers with even greater precision.
Employers can also save search criteria for future use and receive notifications
when new developers matching their criteria join the platform.

3. AI-Powered Candidate Matching: DevSearch incorporates advanced AI


algorithms to analyze job postings and developer profiles, providing
employers with highly accurate candidate recommendations.
Employers can receive personalized suggestions based on the specific
requirements of their projects or job openings.

4. Integrated Coding Assessments: The platform integrates coding


assessment tools, allowing employers to evaluate candidates' technical skills
directly within DevSearch.
This streamlines the screening process and provides employers with
valuable insights into candidates' coding abilities.

19
5. Virtual Collaboration Spaces: DevSearch introduces virtual collaboration
spaces where developers can work together on projects in real-time. These
spaces include features such as code editors, video conferencing, and task
management tools, enabling seamless collaboration regardless of geographical
location.

6. Automated Interview Scheduling: DevSearch automates the interview


scheduling process by allowing employers to set their availability and
preferences directly within the platform.
Candidates can then select a time slot that works for them, eliminating the
back-and-forth communication typically involved in scheduling interviews.

7. Enhanced Privacy Controls: Developers have greater control over the


visibility of their profiles, allowing them to customize who can view
certain sections of their profile.
This ensures that developers can maintain their privacy while still showcasing
their skills to potential employers.

8. Community Q&A Forum: DevSearch introduces a community Q&A forum


where developers can ask questions, seek advice, and share knowledge with
their peers.
This fosters a sense of community and encourages collaboration and learning
among developers.

9. Integrated Learning Platform: DevSearch integrates a learning


platform with access to a curated library of educational resources, including
tutorials, articles, and courses.
Developers can easily access relevant learning materials to enhance their skills
and stay updated on the latest technologies.

10. Enhanced Analytics Dashboard: Employers have access to an


enhanced analytics dashboard that provides insights into the performance of
their job postings, candidate engagement, and hiring metrics.
This allows employers to track the effectiveness of their recruitment efforts and
make data-driven decisions.

20
Overall, the proposed system of DevSearch aims to provide an even more
seamless and efficient experience for both developers and employers, leveraging
advanced technology to facilitate talent discovery, collaboration, and professional
growth within the tech industry.

21
1.6.2) Features of Devsearch:

Certainly! Let's dive into the features of DevSearch in more detail:

1. User Profiles: Developers can create comprehensive profiles showcasing


their skills, experience, education, certifications, and projects. They can also
include a portfolio of their work, GitHub repositories, and links to their
professional social media profiles.

2. Advanced Search: Employers can use advanced search filters to find


developers based on specific criteria such as programming languages,
frameworks, experience level, location, availability, and project type. They can
save search criteria for future use and receive notifications when new developers
match their requirements.

3. AI-Powered Recommendations: DevSearch's recommendation algorithms


analyze project requirements and developer profiles to suggest the most
suitable candidates to employers. Recommendations are personalized based on
the employer's preferences and the developer's skills, experience, and past
collaborations.

4. Collaboration Tools: DevSearch provides collaboration tools such as


messaging, file sharing, version control integration (e.g., GitHub), and project
management features. Developers can communicate with each other, share
code snippets, collaborate on projects, and track progress within the platform.

5. Streamlined Hiring Process: Employers can manage the entire hiring


process within DevSearch, from posting job openings to extending offers. They
can track candidate applications, schedule interviews, and communicate with
candidates directly through the platform, streamlining the hiring workflow and
saving time.

6. Remote Work Support: DevSearch supports remote work by providing tools


for virtual collaboration, communication, and project management. Developers
can work from anywhere and collaborate effectively with team members
regardless of their location.

22
7. Continuous Learning Resources: DevSearch offers a library of educational

23
resources such as online courses, tutorials, articles, and webinars to support
developers in their continuous learning and skill development.

Developers can access relevant learning materials to enhance their skills and stay
updated on the latest technologies.

8. Community Engagement: DevSearch fosters a sense of community by


providing forums, discussion boards, and virtual events where developers can
connect, ask questions, share knowledge, and network with their peers.
Community engagement features encourage collaboration, mentorship, and
professional growth within the developer community.

9. Privacy and Security: DevSearch prioritizes user privacy and security by


implementing robust encryption protocols and data protection measures.
Developers have control over the visibility of their profiles and can choose
which information to share with employers. The platform complies with data
privacy regulations to ensure the confidentiality and integrity of user data.

10. Feedback and Review Mechanism: Employers can provide feedback and
ratings on developers they have worked with, helping to build trust and credibility
within the community. Reviews and ratings contribute to developers' reputations
on the platform and help employers make informed hiring decisions.

These features collectively make DevSearch a comprehensive platform for


developers and employers to connect, collaborate, and succeed in the tech
industry.

24
1.7 Scope

The scope of DevSearch encompasses various aspects of the tech


industry, aiming to address the needs of developers, employers, and the
broader developer community. Here's an overview of its scope:

1. Talent Discovery and Recruitment: DevSearch facilitates the process of


discovering and recruiting talented developers for projects, job openings, or
freelance opportunities. It provides employers with tools to search for
developers based on specific criteria and receive recommendations tailored to
their needs.

2. Developer Profiles and Portfolios: DevSearch allows developers to


create comprehensive profiles showcasing their skills, experience, projects,
and achievements. They can also build portfolios to highlight their work,
GitHub repositories, and contributions to open-source projects.

3. Collaboration and Networking: DevSearch fosters collaboration and


networking among developers by providing communication tools,
collaboration spaces, and community forums. Developers can connect with
peers, share knowledge, collaborate on projects, and participate in discussions
within the platform.

4. Continuous Learning and Skill Development: DevSearch offers a range of


educational resources such as online courses, tutorials, articles, and webinars to
support developers in their continuous learning and skill development journey.
Developers can access relevant learning materials to enhance their skills and
stay updated on the latest technologies.

5. Remote Work Support: DevSearch supports remote work by providing


virtual collaboration tools and communication features. Developers can work
from anywhere and collaborate effectively with team members, regardless of their
geographical location.

6. Streamlined Hiring Process: DevSearch streamlines the hiring process for


employers by offering tools for managing job postings, applications,
interviews, and candidate evaluations within one centralized platform.
25
This saves time and resources for employers and improves the overall efficiency
of the hiring workflow.

7. Privacy and Security: DevSearch prioritizes user privacy and security by


implementing robust encryption protocols, data protection measures, and
privacy controls. Developers have control over the visibility of their profiles and
can choose which information to share with employers, ensuring the
confidentiality and integrity of their data.

8. Feedback and Reviews: DevSearch incorporates a feedback and review


mechanism where employers can provide feedback and ratings on developers
they have worked with. Reviews and ratings contribute to developers' reputations
on the platform and help employers make informed hiring decisions.

Overall, the scope of DevSearch is to provide a comprehensive platform that


connects developers with opportunities, facilitates collaboration and learning,
streamlines the hiring process for employers, and fosters a vibrant and supportive
community within the tech industry.

26
1.8 Outcomes

The outcome of DevSearch encompasses various benefits and impacts


for developers, employers, and the tech industry as a whole. Here's a
detailed overview of the outcomes:

1. For Developers:

- *Increased Visibility*: DevSearch provides developers with a platform to


showcase their skills, projects, and expertise, increasing their visibility to
potential employers.

- Enhanced Opportunities: Developers gain access to a wider range of job


opportunities, freelance projects, and collaboration opportunities within the
tech community.

- Continuous Learning: DevSearch offers a library of educational resources


and networking opportunities to support developers in their continuous learning
and skill development journey.

- Career Growth: Developers can leverage DevSearch to connect with


mentors, receive feedback on their work, and access resources for career
advancement and professional growth.

2. For Employers:

- Efficient Talent Acquisition: Employers can efficiently discover, evaluate,


and recruit skilled developers for their projects or job openings, reducing time-to-
hire and improving hiring efficiency.

- Access to Diverse Talent Pool: DevSearch provides access to a diverse


talent pool with developers from different backgrounds, experiences, and
perspectives, enabling employers to build diverse and inclusive teams.

27
- Streamlined Hiring Process: DevSearch streamlines the hiring process by
offering tools for managing job postings, applications, interviews, and
candidate evaluations within one centralized platform.

- Quality Candidates: Employers receive recommendations and insights on


the most suitable candidates for their projects or job openings, helping them
identify and hire top talent effectively.

3. For the Tech Industry:

- Improved Collaboration: DevSearch fosters collaboration and knowledge


sharing among developers, leading to increased innovation, productivity, and
quality of work within the tech industry.

- Enhanced Skills Development: DevSearch offers a range of educational


resources and networking opportunities to support developers in their
continuous learning and skill development journey, contributing to the overall
skill development of the tech workforce.

- Efficient Talent Marketplace: DevSearch creates a more efficient and


transparent marketplace for talent, connecting developers with opportunities and
employers with skilled professionals, thereby driving growth and innovation in
the tech industry.

- Positive Community Impact: DevSearch contributes to building a vibrant


and supportive community within the tech industry, where developers can
connect, collaborate, and grow together, leading to a positive impact on the
overall ecosystem.

Overall, the outcome of DevSearch is to empower developers, streamline the hiring


process for employers, and contribute to the growth and innovation of the tech
industry through efficient talent discovery, collaboration, and skill development.

28
1.9 Tools and technology used:-

For Frontend

1) HTML:-
● HTML (HyperText Markup Language) is the standard language used to
create and structure content on the web.
● It consists of a series of elements, represented by tags, that define
different parts of a webpage, such as headings, paragraphs, links, images,
and other multimedia.
● HTML tags are written within angle brackets, like <html>, <head>, <body>,
<p>, and <a>. HTML provides the skeleton of a webpage, enabling
browsers to display text, images, and interactive forms in a structured
format.
● Each HTML document begins with a <!DOCTYPE html>
declaration, followed by an <html> element that encompasses the
entire content.
● The <head> section contains metadata, links to stylesheets, and scripts,
while the <body> section includes the actual content displayed to users.
● HTML works in conjunction with CSS (Cascading Style Sheets) for
styling and JavaScript for interactivity, forming the core technologies for
web development.

29
2) CSS:-
● CSS, or Cascading Style Sheets, is a stylesheet language used to describe
the presentation of a document written in HTML or XML.
● CSS defines how elements should be displayed on screen, paper, or in
other media.
● It enables developers to separate content from design, providing a
more flexible and efficient method for designing web pages.
● CSS allows for the styling of multiple elements simultaneously,
promoting consistency across a website.
● It includes features for layout, color, font, spacing, and responsive
design, ensuring that web pages look good on various devices and screen
sizes.
● By using selectors and properties, developers can target HTML elements
and apply specific styles to them.
● CSS can be embedded within HTML documents, included as an external
file, or written inline within HTML tags.
● Its cascading nature means that styles can be applied hierarchically, with
more specific rules overriding more general ones.

30
3) Javascript:-
● JavaScript is a versatile, high-level programming language primarily used
for creating and enhancing interactive elements on websites.
● As a core technology of the World Wide Web, alongside HTML and CSS,
JavaScript enables dynamic content that can respond to user actions, such as
form validations, animated graphics, interactive maps, and real-time
updates.
● Initially developed by Netscape in 1995, JavaScript has evolved
significantly and is now an essential tool for front-end development, often
employed in conjunction with frameworks like React, Angular, and Vue.js.
● Additionally, with the advent of Node.js, JavaScript can also be used
for server-side programming, making it a full-stack language.
● Its syntax is similar to Java and C++, which helps in learning
other programming languages.
● JavaScript's versatility and widespread adoption make it a fundamental
skill for web developers, facilitating the creation of modern, responsive,
and user-friendly web applications.

31
For Backend

Django:-

● Django is a high-level Python web framework designed to facilitate the


rapid creation of robust and scalable web applications.
● It promotes the principle of "Don't Repeat Yourself" (DRY), enabling
developers to focus on writing unique code by providing a wealth of built-
in features.
● Django handles common web development tasks such as database
operations, user authentication, and URL routing, reducing the need for
manual coding.
● It includes an object-relational mapper (ORM) for database interactions, a
powerful templating engine, and an intuitive admin interface for
managing application data. Additionally, Django emphasizes security,
incorporating protections against common web vulnerabilities like SQL
injection and cross-site scripting (XSS).
● Its modular architecture and extensive documentation make it suitable for
both beginners and experienced developers, supporting projects ranging from
simple websites to complex, enterprise-level applications.
● Overall, Django streamlines web development while maintaining
flexibility and scalability.

32
Python:-

● Python is a high-level, interpreted programming language known for its


simplicity, versatility, and readability. Created by Guido van Rossum and
first released in 1991, Python has since become one of the most popular
programming languages worldwide.
● Its syntax is clean and easy to understand, making it an excellent choice
for beginners and experienced developers alike.
● Python's versatility is evident in its wide range of applications. It is
commonly used in web development, with frameworks like Django and Flask
enabling developers to build robust and scalable web applications.
● Additionally, Python's extensive libraries, such as NumPy, pandas, and
matplotlib, make it a popular choice for data analysis and scientific
computing. Its simplicity and ease of use also make it suitable for tasks
like automation, scripting, and rapid prototyping.
● One of Python's key strengths is its extensive standard library, which
provides modules and functions for performing various tasks without the
need for additional installations.
● Moreover, Python's active community continually develops third-party
packages that extend its capabilities even further, covering areas such
as machine learning, natural language processing, and game
development.
● Python's readability stems from its use of indentation to define code
blocks, rather than relying on curly braces or keywords.

33
● This encourages a clean, consistent coding style and reduces the likelihood
of syntax errors. Furthermore, Python's dynamic typing system allows
variables to be assigned without specifying their data types explicitly,
enhancing code flexibility and reducing verbosity.

34
1.10 Project Plan

- Creating a project plan for DevSearch involves outlining the key


phases, tasks, timelines, resources, and milestones involved in the
development and launch of the platform. Here's a high-level
project plan for DevSearch:

- 1. Project Initiation Phase:


- Define project objectives, scope, and requirements.
- Identify key stakeholders and establish communication channels.
- Develop a project charter outlining project goals, timelines,
and responsibilities.
- Conduct initial market research and competitor analysis to understand
the landscape.

2. Planning Phase:
- Develop a detailed project plan outlining tasks, dependencies,
timelines, and resources required for each phase.
- Identify and prioritize features and functionalities based on user needs
and market demand.
- Define technical specifications, architecture, and technology stack for
the platform.
- Establish project milestones and deliverables.

3. Design and Prototyping Phase:


- Design user interface mockups, wireframes, and prototypes based on
the defined requirements.
- Gather feedback from stakeholders and iterate on designs to
ensure usability and user satisfaction.
- Develop a design style guide and branding elements for the platform.
- Finalize the visual design and user experience of the platform.

35
4. Development Phase:
- Develop the backend infrastructure, databases, and APIs required for
the platform.
- Implement frontend components and user interfaces based on the
approved designs.
- Integrate third-party services and tools as needed, such as AI
algorithms, collaboration tools, and communication platforms.
- Conduct regular code reviews, testing, and debugging to ensure quality
and stability.

5. Testing and Quality Assurance Phase:


- Develop test cases and scenarios to validate the functionality,
performance, and security of the platform.
- Conduct comprehensive testing including unit testing, integration
testing, regression testing, and user acceptance testing.
- Address any bugs, issues, or performance bottlenecks identified
during testing.
- Ensure compliance with data privacy regulations and security standards.

6. Deployment Phase:
- Prepare for the deployment of the platform to production servers or
cloud infrastructure.
- Configure deployment pipelines, continuous integration, and
automated deployment processes.
- Perform final checks and validations to ensure a smooth
deployment process.
- Monitor system performance and user feedback post-deployment,
and address any issues as they arise.

7. Launch and Marketing Phase:


- Develop a marketing and communication strategy to promote the launch
of DevSearch.
- Create marketing materials such as website content, blog posts,
social media campaigns, and press releases.
- Engage with potential users, partners, and industry influencers to
generate buzz and interest in the platform.

36
- Monitor user acquisition, engagement, and feedback post-launch,
and iterate on marketing strategies as needed.

8. Post-Launch Maintenance and Support Phase:


- Provide ongoing maintenance, updates, and support for the platform
to address user feedback, bug fixes, and feature enhancements.
- Monitor system performance, security, and scalability, and optimize
as needed to ensure a seamless user experience.
- Continuously iterate on the platform based on user feedback, market
trends, and technological advancements to keep DevSearch competitive
and relevant in the long term.

Throughout the project lifecycle, regular communication, collaboration, and


coordination among team members, stakeholders, and external partners are
essential to ensure the successful development and launch of DevSearch.
Additionally, flexibility and adaptability to changes in requirements, priorities,
and market dynamics are key to overcoming challenges and achieving project
objectives.

37
2. Requirement Analysis
2.1 Feasibility Study

1. Market Demand:- Analyze the demand for developer-focused search


platforms. - Identify target demographics within the developer
community.
2. Competition Analysis:- Evaluate existing developer search tools and
platforms. - Assess their strengths, weaknesses, and market penetration.
- Identify opportunities for differentiation and market positioning.
3. User Needs and Requirements:- Conduct surveys and interviews to
understand developers' pain points and preferences. - Determine the
key features and functionalities required to meet user needs effectively.
4. Technological Feasibility:- Assess the technical requirements for
developing and maintaining DevSearch. - Determine the feasibility of
implementing desired features within the chosen technological stack. -
Evaluate scalability, performance, and compatibility with existing systems
and tools.
5. Cost Analysis:- Estimate the initial development costs, including software
development, infrastructure, and staffing. - Project ongoing operational
expenses, such as maintenance, hosting, and support. - Compare costs
against potential revenue streams or funding sources.
6. Usability and User Experience:- Design and conduct usability tests to
evaluate the user interface and overall user experience. - Incorporate
feedback to optimize navigation, search functionality, and accessibility.
7. Security and Privacy Considerations:- Identify potential security threats
and vulnerabilities. - Implement robust security measures to protect user data
and prevent unauthorized access. - Ensure compliance with relevant privacy
regulations and standards.

38
8. Scalability and Performance:- Assess the platform's ability to handle
increasing user traffic and data volumes. - Implement scalable architecture
and performance optimization techniques. - Conduct stress tests to identify
potential bottlenecks and performance limitations.
9. Pilot Testing and Feedback:- Conduct pilot tests with a small group of
users to gather feedback and iterate on the platform. - Use feedback to refine
features, address usability issues, and improve overall satisfaction.

Conclusion:- Based on the findings, determine the feasibility of developing and


launching DevSearch. - Identify potential risks and mitigation strategies. - Make
recommendations for further development and investment based on the study's
results.

39
2.2 Users of the System:

Devsearch is a web application designed to connect developers with


various projects, job opportunities, and other developers for networking
and collaboration. Users of Devsearch typically fall into several
categories:

1. Individual Developers:

Freelancers: Looking for new projects and clients to work with. They use
Devsearch to find job postings and project opportunities that match their skill sets.

Job Seekers: Developers seeking full-time, part-time, or contract positions. They


use the platform to search for job listings, submit applications, and network with
potential employers.

Learners: New or junior developers aiming to gain experience and build their
portfolios. They use Devsearch to find mentorship opportunities, open-source
projects to contribute to, and learning resources.

2. Employers and Recruiters:

Tech Companies: Businesses in need of software development talent. They use


Devsearch to post job openings, browse developer profiles, and recruit candidates
for various roles.

Recruitment Agencies: Agencies specializing in tech recruitment. They use the


platform to find suitable candidates for their clients' needs.

3. Project Owners and Managers:

Startup Founders: Entrepreneurs looking to build a tech product. They use


Devsearch to find developers with the necessary skills to bring their ideas to life.

Project Managers: Individuals overseeing development projects. They use the


platform to recruit team members, manage collaborations, and ensure project
milestones are met.

40
4. Community Builders and Educators:

Mentors: Experienced developers who offer guidance and support to less


experienced developers. They use Devsearch to connect with mentees
and contribute to the developer community.

Educators: Instructors and trainers who provide coding boot camps, courses, and
workshops. They use the platform to reach potential students and collaborate on
educational content.

41
2.3 Modules

Sure, here's a detailed breakdown of the modules that could be part of


DevSearch:

1. User Authentication and Profile Management:


This module handles user registration, login, and profile management
functionalities. It ensures secure authentication and allows users to update their
profiles, including personal information, preferences, and settings.

2. Search Engine:
The core functionality of DevSearch, this module enables users to search for
programming languages, frameworks, libraries, tools, documentation, tutorials,
articles, and discussions. It utilizes search algorithms and indexing techniques
to provide relevant and accurate search results.

3. Trending Topics and Insights:


This module tracks and analyzes trending topics, discussions, and technologies
within the developer community. It presents insights and analytics to users,
helping them stay updated on the latest trends and developments in the
programming world.

4. Documentation Repository:
DevSearch maintains a comprehensive repository of documentation for various
programming languages, frameworks, and libraries. This module organizes and
categorizes documentation, making it easily accessible to users for reference
and learning purposes.

5. Community Interaction and Collaboration:


This module facilitates community interaction, allowing users to engage in
discussions, ask questions, share insights, and provide feedback. It includes
features such as forums, comment sections, chat functionalities, and social
networking elements to foster collaboration and knowledge sharing among
developers.

6. Recommendation Engine:
Based on user preferences, search history, and behavior, this module provides
personalized recommendations for programming tools, resources, tutorials, and
articles. It utilizes machine learning algorithms and data analysis techniques to
suggest relevant content and enhance the user experience.

42
7. Integration Support with External Tools and Platforms:
DevSearch integrates with other developer tools and platforms, such as IDEs,
version control systems, project management tools, and online repositories. This
module ensures seamless interoperability and allows users to access relevant
information from their preferred tools within the DevSearch ecosystem.

8. Admin Panel and Content Management:


This module is responsible for managing user-generated content, moderating
discussions, and administering the platform. It includes functionalities for
content moderation, user management, analytics, and reporting to ensure the
smooth operation of the platform.

9. Notifications and Alerts:


DevSearch sends notifications and alerts to users for various activities, such as
new discussions, replies to their posts, trending topics, and updates related to
their interests. This module enhances user engagement and keeps users
informed about relevant events within the platform.

10. Analytics and Insights: This module collects and analyzes data related
to user behavior, search patterns, engagement metrics, and platform usage. It
generates insights and reports to help administrators understand user
preferences, identify trends, and make data-driven decisions to improve the
platform.

These modules collectively form the foundation of DevSearch, providing a


comprehensive and user-centric platform for developers to search, discover, and
collaborate on programming-related topics and resources.

43
2.4 Hardware & Software Requirements

Hardware requirements:

● Processor: Minimum Intel core i3


● RAM: Minimum 4GB
● Hard-disk: Minimum 8GB
● Connectivity: Internet connectivity is required

Software requirements:

● VS Code
● Python
● TensorFlow
● NumPy
● IDE (Integrated Development Environment)
● Version Control System (e.g., Git)
● Text Editors (for Documentation)

44
3) Design
3.1) Diagram

3.1.1) DFD

0 level DFD:-

45
1 level DFD:-

46
2 Level DFD:-

47
3.1.2) ER Diagram:-

48
4) Implementation:
4.1) Code:-
4.1.1) HTML Code:-
main.html

<!DOCTYPE html>
{% load static %}
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />

<!-- Favicon -->


<link rel="shortcut icon" href="images/favicon.ico" type="image/x-icon" />
<!-- Icon - IconMonster -->
<link
rel="stylesheet"
href="https://cdn.iconmonstr.com/1.3.0/css/iconmonstr-iconic-font.min.css"
/>
<!-- Mumble UI -->
<link rel="stylesheet" href="{% static 'uikit/styles/uikit.css' %}" />
<!-- Dev Search UI -->
<link rel="stylesheet" href="{% static 'styles/app.css' %}" />

<title>DevSearch - Connect with Developers!</title>


</head>

<body>
<!-- Header Section -->
<header class="header">
<div class="container container--narrow">
<a href="{% url 'profiles' %}" class="header logo">
49
<img src="{% static 'images/logo.svg' %}" alt="DevSearch Logo" />
</a>
<nav class="header nav">
<input type="checkbox" id="responsive-menu" />
<label for="responsive-menu" class="toggle-menu">
<span>Menu</span>
<div class="toggle-menu lines"></div>
</label>
<ul class="header menu">
<li class="header menuItem"><a href="{% url 'profiles'
%}">Developers</a></li>
<li class="header menuItem"><a href="{% url 'projects'
%}">Projects</a></li>

{% if request.user.is_authenticated %}
<li class="header menuItem"><a href="{% url 'account'
%}">Account</a></li>
<li class="header menuItem"><a href="{% url 'inbox' %}">Inbox</a></li>

<li class="header menuItem"><a href="{% url 'logout' %}"


class="btn btn--sub">Logout</a></li>
{% else %}
<li class="header menuItem"><a href="{% url 'login' %}"
class="btn btn--sub">Login/Sign Up</a></li>
{% endif %}

</ul>
</nav>
</div>
</header>

{% if messages %}

50
{% for message in messages %}
<div class="alert alert--{{messgae.tags}}">
<p class="alert message">{{message}}</p>
<button class="alert close">x</button>
</div>
{% endfor %}

{% endif %}

{% block content %} {% endblock content %}

<script src="{% static 'uikit/app.js' %}"></script>


<script src="{% static 'js/main.js' %}"></script>
</body>
</html>

51
index.html

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />

<!-- Favicon -->


<link rel="shortcut icon" href="images/favicon.ico" type="image/x-icon" />
<!-- Icon - IconMonster -->
<link rel="stylesheet"
href="https://cdn.iconmonstr.com/1.3.0/css/iconmonstr-iconic-font.min.css" />
<!-- Mumble UI -->
<link rel="stylesheet" href="uikit/styles/uikit.css" />
<!-- Dev Search UI -->
<link rel="stylesheet" href="styles/app.css" />

<title>DevSearch - Connect with Developers!</title>


</head>

<body>
<!-- Header Section -->
<header class="header">
<div class="container container--narrow">
<a href="/" class="header logo">
<img src="images/logo.svg" alt="DevSearch Logo" />
</a>
<nav class="header nav">
<input type="checkbox" id="responsive-menu" />
52
<label for="responsive-menu" class="toggle-menu">
<span>Menu</span>
<div class="toggle-menu lines"></div>

</label>
<ul class="header menu">
<li class="header menuItem"><a href="index.html">Developers</a></li>
<li class="header menuItem"><a href="projects.html">Projects</a></li>
<li class="header menuItem"><a href="inbox.html">Inbox</a></li>
<li class="header menuItem"><a
href="account.html">My Account</a></li>
<li class="header menuItem"><a href="login.html"
class="btn btn--sub">Login/Sign Up</a></li>
</ul>
</nav>
</div>
</header>

<!-- Main Section -->


<main class="home">
<section class="hero-section text-center">
<div class="container container--narrow">
<div class="hero-section box">
<h2>CONNECT WITH <span>DEVELOPERS</span></h2>
<h2>FROM AROUND THE WORLD</h2>
</div>

<div class="hero-section search">


<form class="form" action="#" method="get">
<div class="form field">
<label for="formInput#search">Search Developers </label>
<input class="input input--text" id="formInput#search" type="text"
name="text"
placeholder="Search by developer name" />
</div>

53
<input class="btn btn--sub btn--lg" type="submit" value="Search" />
</form>
</div>
</div>

</section>
<!-- Search Result: DevList -->
<section class="devlist">
<div class="container">
<div class="grid grid--three">
<div class="column card">
<div class="dev">
<a href="/profile.html" class="card body">
<div class="dev profile">
<img class="avatar avatar--md"
src="https://avatars.githubusercontent.com/u/22437186" alt="image" />
<div class="dev meta">
<h3>Shahriar P. Shuvo</h3>
<h5>FullStack Web Designer & Developer</h5>
</div>
</div>
<p class="dev info">
Lorem ipsum dolor sit, amet consectetur adipisicing elit. Cupiditate,
ducimus inventore! Sunt,
veniam veritatis? Veritatis placeat, deleniti iure tempore veniam
perspiciatis, soluta cupiditate
animi, exercitationem molestias nam doloremque architecto odit.
</p>
<div class="dev skills">
<span class="tag tag--pill tag--main">
<small>JavaScript</small>
</span>
<span class="tag tag--pill tag--main">
<small>React</small>
</span>
<span class="tag tag--pill tag--main">
54
<small>SCSS</small>
</span>
<span class="tag tag--pill tag--main">
<small>Nodejs</small>

</span>
<span class="tag tag--pill tag--main">

<small>Express</small>
</span>
<span class="tag tag--pill tag--main">
<small>GraphQL</small>
</span>
</div>
</a>
</div>
</div>
<div class="column card">
<div class="dev">
<a href="/profile.html" class="card body">
<div class="dev profile">
<img class="avatar avatar--md"
src="https://avatars.githubusercontent.com/u/1868782" alt="image" />
<div class="dev meta">
<h3>Cody Seibert</h3>
<h5>React Developer, Coding Youtuber</h5>
</div>
</div>
<p class="dev info">
Lorem ipsum dolor sit, amet consectetur adipisicing elit. Cupiditate,
ducimus inventore! Sunt,
veniam veritatis? Veritatis placeat, deleniti iure tempore veniam
perspiciatis, soluta cupiditate
animi, exercitationem molestias nam doloremque architecto odit.
55
</p>
<div class="dev skills">
<span class="tag tag--pill tag--main">
<small>Elixir</small>
</span>

<span class="tag tag--pill tag--main">


<small>F#</small>
</span>
<span class="tag tag--pill tag--main">
<small>.NET</small>
</span>

</div>
</a>
</div>
</div>
<div class="column card">
<div class="dev">
<a href="/profile.html" class="card body">
<div class="dev profile">

<img class="avatar avatar--md"


src="https://avatars.githubusercontent.com/u/33843378" alt="image" />
<div class="dev meta">
<h3>Dennis Ivy</h3>
<h5>Python & Django Developer</h5>
</div>
</div>
<p class="dev info">
Lorem ipsum dolor sit, amet consectetur adipisicing elit. Cupiditate,
ducimus inventore! Sunt,
56
veniam veritatis? Veritatis placeat, deleniti iure tempore veniam
perspiciatis, soluta cupiditate
animi, exercitationem molestias nam doloremque architecto odit.
</p>
<div class="dev skills">
<span class="tag tag--pill tag--main">

<small>Python</small>
</span>
<span class="tag tag--pill tag--main">
<small>Django</small>
</span>
<span class="tag tag--pill tag--main">
<small>Rest API</small>
</span>
</div>
</a>

</div>
</div>
<div class="column card">
<div class="dev">

<a href="/profile.html" class="card body">


<div class="dev profile">
<img class="avatar avatar--md"
src="https://avatars.githubusercontent.com/u/22437186" alt="image" />
<div class="dev meta">
<h3>Shahriar P. Shuvo</h3>
<h5>FullStack Web Designer & Developer</h5>
</div>
</div>
<p class="dev info">
57
Lorem ipsum dolor sit, amet consectetur adipisicing elit. Cupiditate,
ducimus inventore! Sunt,
veniam veritatis? Veritatis placeat, deleniti iure tempore veniam
perspiciatis, soluta cupiditate
animi, exercitationem molestias nam doloremque architecto odit.
</p>
<div class="dev skills">

<span class="tag tag--pill tag--main">


<small>JavaScript</small>
</span>
<span class="tag tag--pill tag--main">
<small>React</small>
</span>
<span class="tag tag--pill tag--main">
<small>SCSS</small>
</span>
</div>
</a>
</div>
</div>
<div class="column card">
<div class="dev">
<a href="/profile.html" class="card body">
<div class="dev profile">
<img class="avatar avatar--md"
src="https://avatars.githubusercontent.com/u/22437186" alt="image" />
<div class="dev meta">
<h3>Shahriar P. Shuvo</h3>
<h5>FullStack Web Designer & Developer</h5>
</div>
</div>
<p class="dev info">
Lorem ipsum dolor sit, amet consectetur adipisicing elit. Cupiditate,
ducimus inventore! Sunt,
58
veniam veritatis? Veritatis placeat, deleniti iure tempore veniam
perspiciatis, soluta cupiditate
animi, exercitationem molestias nam doloremque architecto odit.
</p>
<div class="dev skills">
<span class="tag tag--pill tag--main">
<small>JavaScript</small>
</span>

<span class="tag tag--pill tag--main">


<small>React</small>
</span>
<span class="tag tag--pill tag--main">
<small>SCSS</small>
</span>
</div>
</a>
</div>
</div>
<div class="column card">
<div class="dev">
<a href="/profile.html" class="card body">
<div class="dev profile">
<img class="avatar avatar--md"
src="https://avatars.githubusercontent.com/u/22437186" alt="image" />
<div class="dev meta">
<h3>Shahriar P. Shuvo</h3>
<h5>FullStack Web Designer & Developer</h5>
</div>
</div>
<p class="dev info">
Lorem ipsum dolor sit, amet consectetur adipisicing elit. Cupiditate,
ducimus inventore! Sunt,
veniam veritatis? Veritatis placeat, deleniti iure tempore veniam
perspiciatis, soluta cupiditate
59
animi, exercitationem molestias nam doloremque architecto odit.
</p>
<div class="dev skills">
<span class="tag tag--pill tag--main">
<small>JavaScript</small>
</span>
<span class="tag tag--pill tag--main">
<small>React</small>
</span>

<span class="tag tag--pill tag--main">


<small>SCSS</small>
</span>
</div>
</a>
</div>
</div>
</div>
</div>
</section>
<div class="pagination">
<ul class="container">
<li><a href="#" class="btn btn--disabled">&#10094; Prev</a></li>
<li><a href="#" class="btn btn--sub">01</a></li>
<li><a href="#" class="btn">02</a></li>
<li><a href="#" class="btn">03</a></li>
<li><a href="#" class="btn">04</a></li>
<li><a href="#" class="btn">05</a></li>
<li><a href="#" class="btn">06</a></li>
<li><a href="#" class="btn">07</a></li>
<li><a href="#" class="btn">08</a></li>
<li><a href="#" class="btn">09</a></li>
<li><a href="#" class="btn">10</a></li>
<li><a href="#" class="btn">Next &#10095;</a></li>
</ul>
60
</div>
</main>
</body>

</html>

login.html

<!DOCTYPE html>
<html lang="en">

<body>
<div class="auth">
<div class="card">
<div class="auth header text-center">
<a href="/">
<img src="images/icon.svg" alt="icon" />
</a>
<h3>Account Login</h3>
<p>Hello Developer, Welcome Back!</p>
</div>

<form action="#" class="form auth form">


<!-- Input:Email -->
<div class="form field">
<label for="formInput#text">Username: </label>
<input
class="input input--text"
id="formInput#text"
61
type="text"
name="username"
placeholder="Enter your username..."
/>
</div>

<!-- Input:Password -->


<div class="form field">
<label for="formInput#password">Password: </label>
<input

class="input input--password"
id="formInput#passowrd"
type="password"
name="password"
placeholder="••••••••"
/>
</div>
<div class="auth actions">
<input class="btn btn--sub btn--lg" type="submit" value="Log In" />
<a href="forgetpassword.html">Forget Password?</a>
</div>
</form>
<div class="auth alternative">
<p>Don’t have an Account?</p>
<a href="signup.html">Sign Up</a>
</div>
</div>
</div>
</body>
</html>

62
profile.html

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />

<!-- Favicon -->


<link rel="shortcut icon" href="images/favicon.ico" type="image/x-icon" />
<!-- Icon - IconMonster -->
<link rel="stylesheet"
href="https://cdn.iconmonstr.com/1.3.0/css/iconmonstr-iconic-font.min.css" />
<!-- Mumble UI -->
<link rel="stylesheet" href="uikit/styles/uikit.css" />
<!-- Dev Search UI -->
<link rel="stylesheet" href="styles/app.css" />

<title>DevSearch - Connect with Developers!</title>


</head>

<body>
<!-- Header Section -->
<header class="header">
63
<div class="container container--narrow">
<a href="/" class="header logo">
<img src="images/logo.svg" alt="DevSearch Logo" />
</a>
<nav class="header nav">
<input type="checkbox" id="responsive-menu" />
<label for="responsive-menu" class="toggle-menu">
<span>Menu</span>
<div class="toggle-menu lines"></div>
</label>
<ul class="header menu">
<li class="header menuItem"><a href="index.html">Developers</a></li>
<li class="header menuItem"><a href="projects.html">Projects</a></li>

<li class="header menuItem"><a href="inbox.html">Inbox</a></li>


<li class="header menuItem"><a
href="account.html">My Account</a></li>
<li class="header menuItem"><a href="login.html"
class="btn btn--sub">Login/Sign Up</a></li>
</ul>
</nav>
</div>
</header>

<!-- Main Section -->


<main class="profile my-md">
<div class="container">
<div class="layout">
<div class="column column--1of3">
<div class="card text-center">
<div class="card body dev">
<img class="avatar avatar--xl"
src="https://avatars.githubusercontent.com/u/33843378" />
<h2 class="dev name">Dennis Ivanov</h2>
<p class="dev title">Expirance FullStack Developer, Youtuber
and Instructor</p>
<p class="dev location">Based in Florida, USA</p>
<ul class="dev social">
<li>
64
<a title="Github" href="#" target="_blank"><i
class="im im-github"></i></a>
</li>
<li>
<a title="Stackoverflow" href="#" target="_blank"><i
class="im im-stackoverflow"></i></a>
</li>
<li>
<a title="Twitter" href="#" target="_blank"><i
class="im im-twitter"></i></a>
</li>
<li>
<a title="LinkedIn" href="#" target="_blank"><i
class="im im-linkedin"></i></a>
</li>

<li>
<a title="Personal Website" href="#" target="_blank"><i class="im
im-globe"></i></a>
</li>
</ul>
<a href="#" class="btn btn--sub btn--lg">Send Message </a>
</div>
</div>
</div>
<div class="column column--2of3">
<div class="devInfo">
<h3 class="devInfo title">About Me</h3>
<p class="devInfo about">
Lorem, ipsum dolor sit amet consectetur adipisicing elit. Ex illum ipsum
iusto consequatur. Totam,
dolorum fugiat, debitis facere illo nostrum nesciunt maxime, deserunt enim
voluptatibus modi natus velit
voluptatum. Dicta eritatis exercitationem ut quos a placeat obcaecati?
Architecto illum!
<br />
Amet consectetur adipisicing elit. Veritatis exercitationem ut quos a placeat
obcaecati? Architecto
illum, atque delectus nemo dolorem inventore ab facilis? Dolor placeat vel
delectus ipsam ullam.
65
</p>
</div>
<div class="devInfo">
<h3 class="devInfo title">Skills</h3>
<div class="devInfo skills">
<div class="devSkill">
<h4 class="devSkill title">JavaScript</h4>
<p class="devSkill info">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Recusandae
neque voluptatum ut? Quaerat, ea
cumque! Dolorum provident esse molestias commodi odit sapiente quod
quasi corrupti obcaecati? Nobis
ex temporibus quaerat!
</p>
</div>
<div class="devSkill">

<h4 class="devSkill title">React</h4>


<p class="devSkill info">
Smet consectetur adipisicing elit. Omnis, nihil? Accusamus aspernatur
aut debitis vitae quaerat
nihil fugiat, doloremque nesciunt alias pariatur maxime unde, nam saepe
laborum at odit labore.
</p>
</div>
<div class="devSkill">
<h4 class="devSkill title">Express(Nodejs)</h4>
<p class="devSkill info">
Auae error deleniti aperiam enim nisi nesciunt, ratione eveniet eos fuga
ad recusandae mollitia!
Facere earum, distinctio nihil recusandae ipsum nesciunt. Possimus, ex.
Officia maxime nihil
inventore cum tenetur! Veritatis sapiente libero ducimus nesciunt
itaque, placeat inventore sint
blanditiis?
</p>
</div>

<h3 class="devInfo subtitle">Other Skills</h3>


<div class="devInfo otherSkills">
66
<span class="tag tag--pill tag--sub tag--lg">
<small>Figma</small>
</span>
<span class="tag tag--pill tag--sub tag--lg">
<small>Vuejs</small>
</span>
<span class="tag tag--pill tag--sub tag--lg">
<small>REST API</small>
</span>
<span class="tag tag--pill tag--sub tag--lg">
<small>GraphQL</small>
</span>
<span class="tag tag--pill tag--sub tag--lg">
<small>TypeScript</small>
</span>
<span class="tag tag--pill tag--sub tag--lg">
<small>Webpack</small>

</span>
<span class="tag tag--pill tag--sub tag--lg">
<small>NextJS</small>
</span>
<span class="tag tag--pill tag--sub tag--lg">
<small>Postgres</small>
</span>
<span class="tag tag--pill tag--sub tag--lg">
<small>MongoDB</small>
</span>
</div>
</div>
</div>
<div class="devInfo">
<h3 class="devInfo title">Projects</h3>
<div class="grid grid--two">

<div class="column">
<div class="card project">
<a href="single-project.html" class="project">
<img class="project thumbnail" src="images/project-b.png"
alt="project thumbnail" />
67
<div class="card body">
<h3 class="project title">DevSearch UI Design</h3>
<p><a class="project author" href="profile.html">By Shahriar
P. Shuvo</a></p>
<p class="project--rating">
<span style="font-weight: bold;">92%</span> Postitive
Feedback (62 Votes)
</p>
<div class="project tags">
<span class="tag tag--pill tag--main">
<small>NextJS</small>
</span>
<span class="tag tag--pill tag--main">
<small>GraphQL</small>
</span>
<span class="tag tag--pill tag--main">
<small>TypeScript</small>
</span>

</div>
</div>
</a>
</div>
</div>

<div class="column">
<div class="card project">
<a href="single-project.html" class="project">
<img class="project thumbnail" src="images/project-
c.png" alt="project thumbnail" />
<div class="card body">
<h3 class="project title">Another Landing Page</h3>
<p><a class="project author" href="profile.html">By
Dennis Ivanov</a></p>
<p class="project--rating">
<span style="font-weight: bold;">36%</span> Postitive
Feedback (18 Votes)
</p>
<div class="project tags">
<span class="tag tag--pill tag--main">
68
<small>NextJS</small>
</span>
<span class="tag tag--pill tag--main">
<small>GraphQL</small>
</span>
<span class="tag tag--pill tag--main">
<small>TypeScript</small>
</span>
</div>
</div>
</a>
</div>
</div>

<div class="column">
<div class="card project">
<a href="single-project.html" class="project">
<img class="project thumbnail" src="images/project-
a.png" alt="project thumbnail" />

<div class="card body">


<h3 class="project title">Yoga Studio Landing Page Website and
Design</h3>
<p><a class="project author" href="profile.html">By Dennis
Ivanov</a></p>
<p class="project--rating">
<span style="font-weight: bold;">98%</span> Postitive
Feedback (72 Votes)
</p>
<div class="project tags">
<span class="tag tag--pill tag--main">
<small>NextJS</small>
</span>
<span class="tag tag--pill tag--main">
<small>GraphQL</small>
</span>
<span class="tag tag--pill tag--main">
<small>TypeScript</small>
</span>
</div>
69
</div>
</a>
</div>
</div>

</div>
</div>
</div>
</div>
</div>
</main>
</body>

</html>

4.1.2) Python Code:-

views.py

from django.shortcuts import render, redirect


from django.contrib.auth import login, authenticate, logout
from django.contrib import messages
from django.contrib.auth.models import User
from .forms import CustomUserCreationForm, ProfileForm, SkillForm,
MessageForm
from .models import Profile, skill, Message
from django.db.models import Q
from django.contrib.auth.decorators import login_required
from .utils import searchProfile, paginateProfile

# Create your views here.

def loginUser(request):
70
# This if condition will check if the user is loged in and if its true and then if the
user tries to access the login page by search bar it will restrict and redirect it to the
profiles page
if request.user.is_authenticated:
return redirect('profiles')

if request.method == 'POST':
page = 'login'
username = request.POST['username'].lower()
password = request.POST['password']

try:
user = User.objects.get(username=username)
except:
messages.error(request, "User doesn't exist")

user = authenticate(request, username=username, password=password)

if user is not None:

login(request, user)
return redirect(request.GET['next'] if 'next' in request.GET else 'account')

else:
messages.error(request, "User or password is wrong")

return render(request,

'users/login_register.html') def

logoutUser(request):
logout(request)
messages.info(request, "User successfully loged out")
return redirect('login')
71
def registerUser(request):

72
page = 'register'
form = CustomUserCreationForm()

if request.method == 'POST':
form = CustomUserCreationForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
user.username = user.username.lower()
user.save()

messages.success(request, "User account was created!")

login(request, user)
return redirect('edit-account')

else:
messages.error(request, "An error has been occurred during reqistration")

context = {'page': page, 'form': form}


return render(request, 'users/login_register.html', context)

def profiles(request):

profiles , search_query = searchProfile(request)

custom_range, profiles = paginateProfile(request, profiles, 6)

context = {'profiles': profiles, "search_query": search_query, 'custom_range':


custom_range}
return render(request, 'users/profiles.html', context)

def singleProfile(request, pk):


profile = Profile.objects.get(id = pk)

topskills = profile.skill_set.exclude(description exact="")


otherskills = profile.skill_set.filter(description="")

73
context = {"profile": profile, "topskills": topskills, "otherskills": otherskills}
return render(request, 'users/single-profile.html', context)

@login_required(login_url="login")
def userAccount(request):
profile = request.user.profile

skills = profile.skill_set.all()
projects = profile.project_set.all()

context = {"profile": profile, "skills": skills, "projects": projects}


return render(request, 'users/account.html', context)

@login_required(login_url="login")
def editAccount(request):
profile = request.user.profile
form = ProfileForm(instance=profile)

if request.method == 'POST':
form = ProfileForm(request.POST, request.FILES,
instance=profile) if form.is_valid():
form.save()

return redirect("account")

context = {"form": form}


return render(request, "users/profile_form.html", context)

@login_required(login_url='login')
def createSkill(request):
profile = request.user.profile
form = SkillForm()

if request.method == 'POST':
form = SkillForm(request.POST)
if form.is_valid():
skill = form.save(commit=False)
skill.owner = profile
skill.save()
74
messages.success(request, "skill was added successfully!")
return redirect("account")

context = {'form': form}


return render(request, "users/skill_form.html", context)

@login_required(login_url='login')
def updateSkill(request, pk):
profile = request.user.profile
skill = profile.skill_set.get(id=pk)
form = SkillForm(instance=skill)

if request.method == 'POST':
form = SkillForm(request.POST, instance=skill)
if form.is_valid():
form.save()
messages.success(request, "skill was updated successfully!")
return redirect("account")

context = {'form': form}


return render(request, "users/skill_form.html", context)

@login_required(login_url='login')
def deleteSkill(request, pk):
profile = request.user.profile
skill = profile.skill_set.get(id=pk)

if request.method == 'POST':
skill.delete()
messages.success(request, "Skill was deleted successfully!")
return redirect('account')

context = {'object': skill}


return render(request, 'delete_form.html', context)

@login_required(login_url='login')
75
def inbox(request):
profile = request.user.profile
messageRequest = profile.messages.all()
unreadCount = messageRequest.filter(is_read = False).count()
context = {'messageRequest': messageRequest, 'unreadCount': unreadCount}
return render(request, 'users/inbox.html', context)

@login_required(login_url='login')
def viewMessage(request, pk):
profile = request.user.profile
message = profile.messages.get(id=pk)
if message.is_read == False:
message.is_read = True
message.save()
context = {'message': message}
return render(request, 'users/message.html', context)

def createMessage(request, pk):


recipient = Profile.objects.get(id=pk)
form = MessageForm()

try:
sender = request.user.profile

except:
sender = None

if request.method == 'POST':
form = MessageForm(request.POST)
if form.is_valid():
message = form.save(commit=False)
message.sender = sender
message.recipient = recipient

if sender:
message.name = sender.name
message.email = sender.email
message.save()
76
messages.success(request, "Your message was successfully sent!")
return redirect('single-profile', pk=recipient.id)

context= {'recipient': recipient, 'form': form}


return render(request, 'users/message_form.html', context)

form.py

from django.forms import ModelForm


from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from .models import Profile, skill, Message

class CustomUserCreationForm(UserCreationForm):
class Meta:
model = User
fields = ['first_name', 'email', 'username', 'password1', 'password2']
labels = {
'first_name': 'Name',
77
}

def init (self, *args, **kwargs):


super(CustomUserCreationForm, self). init (*args, **kwargs)

for name, field in self.fields.items():


field.widget.attrs.update({'class': 'input'})

class ProfileForm(ModelForm):
class Meta:
model = Profile
fields = ['name', 'email', 'username', 'location', 'short_intro', 'bio', 'profile_image',
'social_github', 'social_linkedin', 'social_twitter', 'social_website', ]

def init (self, *args, **kwargs):


super(ProfileForm, self). init (*args, **kwargs)

for name, field in self.fields.items():


field.widget.attrs.update({'class': 'input'})

class SkillForm(ModelForm):
class Meta:
model = skill
fields = ' all '
exclude = ['owner']

def init (self, *args, **kwargs):


super(SkillForm, self). init (*args, **kwargs)

for name, field in self.fields.items():


field.widget.attrs.update({'class': 'input'})

class MessageForm(ModelForm):
class Meta:
model = Message
fields = ['name', 'email', 'subject', 'body']

78
def init (self, *args, **kwargs):
super(MessageForm, self). init (*args, **kwargs)

for name, field in self.fields.items():


field.widget.attrs.update({'class': 'input'})

admin.py

from django.contrib import admin


from .models import Project, Tags, Review
# Register your models here.

admin.site.register(Project)
admin.site.register(Review)
admin.site.register(Tags)

79
urls.py

from django.contrib import


admin from django.urls import
path from . import views

urlpatterns = [
# path('', views.home, name='home'),
path('', views.projects, name='projects'),
path('single_projects/<str:pk>/', views.single_projects,
name='single_projects'), path('create-project/', views.create_project,
name='create-project'),
path('update-project/<str:pk>/', views.update_project, name='update-
project'), path('delete-project/<str:pk>/', views.delete_project, name='delete-
project'),
]

typing_extensions.py

import abc
import collections
import collections.abc
import functools
import inspect
import operator
80
import sys

81
import types as _types
import typing
import warnings

all = [
# Super-special typing primitives.
'Any',
'ClassVar',
'Concatenate',
'Final',
'LiteralString',
'ParamSpec',
'ParamSpecArgs',
'ParamSpecKwargs',
'Self',
'Type',
'TypeVar',
'TypeVarTuple',
'Unpack',

# ABCs (from collections.abc).


'Awaitable',
'AsyncIterator',
'AsyncIterable',
'Coroutine',
'AsyncGenerator',
'AsyncContextManager',
'Buffer',
'ChainMap',

# Concrete collection types.


'ContextManager',
'Counter',
'Deque',
'DefaultDict',
'NamedTuple',
'OrderedDict',
'TypedDict',
82
# Structural checks, a.k.a. protocols.
'SupportsAbs',
'SupportsBytes',
'SupportsComplex',
'SupportsFloat',
'SupportsIndex',
'SupportsInt',
'SupportsRound',

# One-off things.
'Annotated',
'assert_never',
'assert_type',
'clear_overloads',
'dataclass_transform',
'deprecated',
'get_overloads',
'final',
'get_args',
'get_origin',
'get_original_bases',
'get_protocol_members',
'get_type_hints',
'IntVar',
'is_protocol',
'is_typeddict',
'Literal',
'NewType',
'overload',
'override',

'Protocol',
'reveal_type',
'runtime',
'runtime_checkable',
'Text',
'TypeAlias',
'TypeAliasType',
83
'TypeGuard',
'TYPE_CHECKING',
'Never',
'NoReturn',
'Required',
'NotRequired',

# Pure aliases, have always been in typing


'AbstractSet',
'AnyStr',
'BinaryIO',
'Callable',
'Collection',
'Container',
'Dict',
'ForwardRef',
'FrozenSet',
'Generator',
'Generic',
'Hashable',
'IO',
'ItemsView',
'Iterable',
'Iterator',
'KeysView',
'List',
'Mapping',
'MappingView',
'Match',
'MutableMapping',
'MutableSequence',
'MutableSet',

'Optional',
'Pattern',
'Reversible',
'Sequence',
'Set',
'Sized',
84
'TextIO',
'Tuple',
'Union',
'ValuesView',
'cast',
'no_type_check',
'no_type_check_decorator',
]

# for backward compatibility


PEP_560 = True
GenericMeta = type

# The functions below are modified copies of typing internal helpers.


# They are needed by _ProtocolMeta and they provide support for PEP 646.

class _Sentinel:
def repr (self):
return "<sentinel>"

_marker = _Sentinel()

def _check_generic(cls, parameters, elen=_marker):


"""Check correct count for parameters of a generic cls (internal helper).
This gives a nice error message in case of count mismatch.
"""
if not elen:
raise TypeError(f"{cls} is not a generic class")
if elen is _marker:
if not hasattr(cls, " parameters ") or not cls. parameters :

raise TypeError(f"{cls} is not a generic


class") elen = len(cls. parameters )
alen = len(parameters)
if alen != elen:
if hasattr(cls, " parameters "):
85
parameters = [p for p in cls. parameters if not _is_unpack(p)]
num_tv_tuples = sum(isinstance(p, TypeVarTuple) for p in
parameters) if (num_tv_tuples > 0) and (alen >= elen -
num_tv_tuples):
return
raise TypeError(f"Too {'many' if alen > elen else 'few'} parameters for {cls};"
f" actual {alen}, expected {elen}")

if sys.version_info >= (3, 10):


def _should_collect_from_parameters(t):
return isinstance(
t, (typing._GenericAlias, _types.GenericAlias, _types.UnionType)
)
elif sys.version_info >= (3, 9):
def _should_collect_from_parameters(t):
return isinstance(t, (typing._GenericAlias, _types.GenericAlias))
else:
def _should_collect_from_parameters(t):
return isinstance(t, typing._GenericAlias) and not t._special

def _collect_type_vars(types, typevar_types=None):


"""Collect all type variable contained in types in order of
first appearance (lexicographic order). For example::

_collect_type_vars((T, List[S, T])) == (T, S)


"""
if typevar_types is None:
typevar_types = typing.TypeVar
tvars = []
for t in types:
if (
isinstance(t, typevar_types) and
t not in tvars and

not _is_unpack(t)
):
tvars.append(t)
86
if _should_collect_from_parameters(t):

87
tvars.extend([t for t in t. parameters if t not in tvars])
return tuple(tvars)

NoReturn = typing.NoReturn

# Some unconstrained type variables. These are used by the container types.
# (These are not for export.)
T = typing.TypeVar('T') # Any type.
KT = typing.TypeVar('KT') # Key
type.
VT = typing.TypeVar('VT') # Value type.
T_co = typing.TypeVar('T_co', covariant=True) # Any type covariant containers.
T_contra = typing.TypeVar('T_contra', contravariant=True) # Ditto contravariant.

if sys.version_info >= (3, 11):


from typing import Any
else:

class _AnyMeta(type):
def instancecheck (self, obj):
if self is Any:
raise TypeError("typing_extensions.Any cannot be used with
isinstance()") return super(). instancecheck (obj)

def repr (self):


if self is Any:
return "typing_extensions.Any"
return super(). repr ()

class Any(metaclass=_AnyMeta):
"""Special type indicating an unconstrained type.
- Any is compatible with every type.
- Any assumed to have all methods.
- All values assumed to be instances of Any.

Note that all the above statements are true from the point of view of
static type checkers. At runtime, Any should not be used with instance
88
checks.

89
"""
def new (cls, *args,
**kwargs): if cls is Any:
raise TypeError("Any cannot be
instantiated") return super(). new (cls,
*args, **kwargs)

ClassVar = typing.ClassVar

class _ExtensionsSpecialForm(typing._SpecialForm,
_root=True): def repr (self):
return 'typing_extensions.' + self._name

# On older versions of typing there is an internal class named "Final".


# 3.8+
if hasattr(typing, 'Final') and sys.version_info[:2] >= (3, 7):
Final = typing.Final
# 3.7
else:
class _FinalForm(_ExtensionsSpecialForm,
_root=True): def getitem (self, parameters):
item = typing._type_check(parameters,
f'{self._name} accepts only a single type.')
return typing._GenericAlias(self, (item,))

Final = _FinalForm('Final',
doc="""A special typing construct to indicate that a name
cannot be re-assigned or overridden in a subclass.
For example:

MAX_SIZE: Final = 9000


MAX_SIZE += 1 # Error reported by type checker

class Connection:
TIMEOUT: Final[int] = 10

class FastConnector(Connection):
90
TIMEOUT = 1 # Error reported by type checker

91
There is no runtime checking of these properties.""")

if sys.version_info >= (3, 11):


final = typing.final
else:
# @final exists in 3.8+, but we backport it for all
versions # before 3.11 to keep support for the final
attribute. # See
https://bugs.python.org/issue46342
def final(f):
"""This decorator can be used to indicate to type checkers that
the decorated method cannot be overridden, and decorated class
cannot be subclassed. For example:

class Base:
@final
def done(self) -> None:
...
class Sub(Base):
def done(self) -> None: # Error reported by type checker
...
@final
class Leaf:
...
class Other(Leaf): # Error reported by type checker
...

There is no runtime checking of these properties. The decorator


sets the `` final `` attribute to ``True`` on the decorated
object to allow runtime introspection.
"""
try:
f. final = True
except (AttributeError, TypeError):
# Skip the attribute silently if it is not writable.
# AttributeError happens if the object has slots or a
# read-only property, TypeError if it's a builtin class.

92
pass

93
return f

def IntVar(name):
return typing.TypeVar(name)

# A Literal bug was fixed in 3.11.0, 3.10.1 and 3.9.8


if sys.version_info >= (3, 10, 1):
Literal = typing.Literal
else:
def _flatten_literal_params(parameters):
"""An internal helper for Literal creation: flatten Literals among parameters"""
params = []
for p in parameters:
if isinstance(p,
_LiteralGenericAlias):
params.extend(p. args )
else:
params.append(p)
return tuple(params)

def _value_and_type_iter(params):
for p in params:
yield p, type(p)

class _LiteralGenericAlias(typing._GenericAlias,
_root=True): def eq (self, other):
if not isinstance(other, _LiteralGenericAlias):
return NotImplemented
these_args_deduped = set(_value_and_type_iter(self. args ))
other_args_deduped = set(_value_and_type_iter(other. args ))
return these_args_deduped == other_args_deduped

def hash (self):


return hash(frozenset(_value_and_type_iter(self. args )))

class _LiteralForm(_ExtensionsSpecialForm,
_root=True): def init (self, doc: str):
self._name = 'Literal'

94
self._doc = self. doc = doc

def getitem (self, parameters):


if not isinstance(parameters, tuple):
parameters = (parameters,)

parameters = _flatten_literal_params(parameters)

val_type_pairs = list(_value_and_type_iter(parameters))
try:
deduped_pairs = set(val_type_pairs)
except TypeError:
# unhashable parameters
pass
else:
# similar logic to typing._deduplicate on Python 3.9+
if len(deduped_pairs) < len(val_type_pairs):
new_parameters = []
for pair in val_type_pairs:
if pair in deduped_pairs:
new_parameters.append(pair[0])
deduped_pairs.remove(pair)
assert not deduped_pairs, deduped_pairs
parameters = tuple(new_parameters)

return _LiteralGenericAlias(self, parameters)

Literal = _LiteralForm(doc="""\
A type that can be used to indicate to type checkers
that the corresponding value has a value literally equivalent
to the provided parameter. For example:

var: Literal[4] = 4

The type checker understands that 'var' is literally equal to


the value 4 and no other value.

Literal[...] cannot be subclassed. There is no runtime


checking verifying that the parameter is actually a value
instead of a type.""")

95
_overload_dummy = typing._overload_dummy

if hasattr(typing, "get_overloads"): # 3.11+


overload = typing.overload
get_overloads = typing.get_overloads
clear_overloads =
typing.clear_overloads
else:
# {module: {qualname: {firstlineno: func}}}
_overload_registry =
collections.defaultdict( functools.partial(coll
ections.defaultdict, dict)
)

def overload(func):
"""Decorator for overloaded functions/methods.

In a stub file, place two or more stub definitions for the same
function in a row, each decorated with @overload. For example:

@overload
def utf8(value: None) -> None: ...
@overload
def utf8(value: bytes) -> bytes: ...
@overload
def utf8(value: str) -> bytes: ...

In a non-stub file (i.e. a regular .py file), do the same but


follow it with an implementation. The implementation should *not*
be decorated with @overload. For example:

@overload
def utf8(value: None) -> None: ...
@overload
def utf8(value: bytes) -> bytes: ...
@overload
def utf8(value: str) -> bytes: ...
def utf8(value):
# implementation goes here
96
The overloads for a function can be retrieved at runtime using the
get_overloads() function.
"""
# classmethod and staticmethod
f = getattr(func, " func ", func)
try:
_overload_registry[f. module ][f. qualname ][
f. code .co_firstlineno
] = func
except AttributeError:
# Not a normal function; ignore.
pass
return _overload_dummy

def get_overloads(func):
"""Return all defined overloads for *func* as a
sequence.""" # classmethod and staticmethod
f = getattr(func, " func ", func)
if f. module not in _overload_registry:
return []
mod_dict = _overload_registry[f. module ]
if f. qualname not in mod_dict:
return []
return list(mod_dict[f. qualname ].values())

def clear_overloads():
"""Clear all overloads in the registry."""
_overload_registry.clear()

# This is not a real generic class. Don't use outside annotations.


Type = typing.Type

# Various ABCs mimicking those in collections.abc.


# A few are simply re-exported for completeness.

Awaitable = typing.Awaitable
Coroutine = typing.Coroutine
97
AsyncIterable =
typing.AsyncIterable AsyncIterator =
typing.AsyncIterator Deque =
typing.Deque
ContextManager = typing.ContextManager
AsyncContextManager = typing.AsyncContextManager
DefaultDict = typing.DefaultDict

# 3.7.2+
if hasattr(typing, 'OrderedDict'):
OrderedDict = typing.OrderedDict
# 3.7.0-3.7.2
else:
OrderedDict = typing._alias(collections.OrderedDict, (KT, VT))

Counter = typing.Counter
ChainMap = typing.ChainMap
AsyncGenerator = typing.AsyncGenerator
Text = typing.Text
TYPE_CHECKING = typing.TYPE_CHECKING

_PROTO_ALLOWLIST = {
'collections.abc': [
'Callable', 'Awaitable', 'Iterable', 'Iterator', 'AsyncIterable',
'Hashable', 'Sized', 'Container', 'Collection', 'Reversible', 'Buffer',
],
'contextlib': ['AbstractContextManager', 'AbstractAsyncContextManager'],
'typing_extensions': ['Buffer'],
}

_EXCLUDED_ATTRS = {
" abstractmethods ", " annotations ", " weakref ", "_is_protocol",
"_is_runtime_protocol", " dict ", " slots ", " parameters ",
" orig_bases ", " module ", "_MutableMapping marker", " doc ",
" subclasshook ", " orig_class ", " init ", " new ",
" protocol_attrs ", " callable_proto_members_only ",
98
}

99
if sys.version_info < (3, 8):

_EXCLUDED_ATTRS |= {
"_gorg", " next_in_mro ", " extra ", " tree_hash ", " args ",
" origin "
}

if sys.version_info >= (3, 9):


_EXCLUDED_ATTRS.add(" class_getitem ")

if sys.version_info >= (3, 12):


_EXCLUDED_ATTRS.add(" type_params ")

_EXCLUDED_ATTRS = frozenset(_EXCLUDED_ATTRS)

def _get_protocol_attrs(cls):
attrs = set()
for base in cls. mro [:-1]: # without object
if base. name in {'Protocol', 'Generic'}:
continue
annotations = getattr(base, ' annotations ', {})
for attr in (*base. dict , *annotations):
if (not attr.startswith('_abc_') and attr not in _EXCLUDED_ATTRS):
attrs.add(attr)
return attrs

def _maybe_adjust_parameters(cls):
"""Helper function used in Protocol. init_subclass and
_TypedDictMeta. new .

The contents of this function are very similar


to logic found in typing.Generic. init_subclass
on the CPython main branch.
"""
tvars = []
if ' orig_bases ' in cls. dict :
tvars = _collect_type_vars(cls. orig_bases )
100
# Look for Generic[T1, ..., Tn] or Protocol[T1, ..., Tn].
# If found, tvars must be a subset of it.

# If not found, tvars is it.


# Also check for and reject plain Generic,
# and reject multiple Generic[...] and/or Protocol[...].
gvars = None
for base in cls. orig_bases :
if (isinstance(base, typing._GenericAlias) and
base. origin in (typing.Generic, Protocol)):
# for error messages
the_base = base. origin . name
if gvars is not None:
raise TypeError(
"Cannot inherit from Generic[...]"
" and/or Protocol[...] multiple types.")
gvars = base. parameters
if gvars is None:
gvars = tvars
else:
tvarset = set(tvars)
gvarset = set(gvars)
if not tvarset <= gvarset:
s_vars = ', '.join(str(t) for t in tvars if t not in gvarset)
s_args = ', '.join(str(g) for g in gvars)
raise TypeError(f"Some type variables ({s_vars}) are"
f" not listed in {the_base}[{s_args}]")
tvars = gvars
cls. parameters = tuple(tvars)

def _caller(depth=2):
try:
return sys._getframe(depth).f_globals.get(' name ', ' main ')
except (AttributeError, ValueError): # For platforms without
_getframe()
return None

101
# The performance of runtime-checkable protocols is significantly improved on

102
Python 3.12,
# so we backport the 3.12 version of Protocol to Python <=3.11
if sys.version_info >= (3, 12):
Protocol = typing.Protocol

else:
def _allow_reckless_class_checks(depth=3):
"""Allow instance and class checks for special stdlib modules.
The abc and functools modules indiscriminately call isinstance() and
issubclass() on the whole MRO of a user class, which may contain protocols.
"""
return _caller(depth) in {'abc', 'functools', None}

def _no_init(self, *args,


**kwargs): if
type(self)._is_protocol:
raise TypeError('Protocols cannot be instantiated')

if sys.version_info >= (3, 8):


# Inheriting from typing._ProtocolMeta isn't actually desirable,
# but is necessary to allow typing.Protocol and typing_extensions.Protocol
# to mix without getting TypeErrors about "metaclass conflict"
_typing_Protocol = typing.Protocol
_ProtocolMetaBase = type(_typing_Protocol)
else:
_typing_Protocol = _marker
_ProtocolMetaBase = abc.ABCMeta

class _ProtocolMeta(_ProtocolMetaBase):
# This metaclass is somewhat unfortunate,
# but is necessary for several reasons...
#
# NOTE: DO NOT call super() in any methods in this class
# That would call the methods on typing._ProtocolMeta on Python 3.8-3.11
# and those are slow
def new (mcls, name, bases, namespace,
**kwargs): if name == "Protocol" and len(bases) < 2:
pass
elif {Protocol, _typing_Protocol} & set(bases):
for base in bases:
103
if not (

104
base in {object, typing.Generic, Protocol, _typing_Protocol}
or base. name in _PROTO_ALLOWLIST.get(base. module ,
[])
or is_protocol(base)

):
raise TypeError(
f"Protocols can only inherit from other protocols, "
f"got {base!r}"
)
return abc.ABCMeta. new (mcls, name, bases, namespace, **kwargs)

def init (cls, *args, **kwargs):


abc.ABCMeta. init (cls, *args,
**kwargs) if getattr(cls, "_is_protocol",
False):
cls. protocol_attrs = _get_protocol_attrs(cls)
# PEP 544 prohibits using issubclass()
# with protocols that have non-method
members. cls.
callable_proto_members_only = all(
callable(getattr(cls, attr, None)) for attr in cls. protocol_attrs
)

def subclasscheck (cls, other):


if cls is Protocol:
return type. subclasscheck (cls, other)
if (
getattr(cls, '_is_protocol', False)
and not _allow_reckless_class_checks()
):
if not isinstance(other, type):
# Same error message as for issubclass(1, int).
raise TypeError('issubclass() arg 1 must be a
class')
if (
not cls. callable_proto_members_only
and cls. dict .get(" subclasshook ") is _proto_hook
):
105
raise TypeError(
"Protocols with non-method members don't support issubclass()"
)

106
if not getattr(cls, '_is_runtime_protocol', False):
raise TypeError(
"Instance and class checks can only be used with "
"@runtime_checkable protocols"
)

return abc.ABCMeta. subclasscheck (cls, other)

def instancecheck (cls, instance):


# We need this method for situations where attributes
are # assigned in init .
if cls is Protocol:
return type. instancecheck (cls, instance)
if not getattr(cls, "_is_protocol", False):
# i.e., it's a concrete subclass of a protocol
return abc.ABCMeta. instancecheck (cls, instance)

if (
not getattr(cls, '_is_runtime_protocol', False) and
not _allow_reckless_class_checks()
):
raise TypeError("Instance and class checks can only be used
with" " @runtime_checkable protocols")

if abc.ABCMeta. instancecheck (cls, instance):


return True

for attr in cls. protocol_attrs :


try:
val = inspect.getattr_static(instance, attr)
except AttributeError:
break
if val is None and callable(getattr(cls, attr, None)):
break
else:
return True

return False

107
def eq (cls, other):
# Hack so that typing.Generic. class_getitem
# treats typing_extensions.Protocol
# as equivalent to typing.Protocol on Python
3.8+ if abc.ABCMeta. eq (cls, other) is
True:
return True

return (
cls is Protocol and other is getattr(typing, "Protocol", object())
)

# This has to be defined, or the abc-module cache


# complains about classes with this metaclass being
unhashable, # if we define only eq !
def hash (cls) -> int:
return type. hash (cls)

@classmethod
def _proto_hook(cls, other):
if not cls. dict .get('_is_protocol', False):
return NotImplemented

for attr in cls. protocol_attrs :


for base in other. mro :
# Check if the members appears in the class
dictionary... if attr in base. dict :
if base. dict [attr] is None:
return NotImplemented
break

# ...or in annotations, if it is a sub-protocol.


annotations = getattr(base, ' annotations ', {})
if (
isinstance(annotations, collections.abc.Mapping)
and attr in annotations
and is_protocol(other)
): else:

108
break

109
return NotImplemented
return True

if sys.version_info >= (3, 8):


class Protocol(typing.Generic, metaclass=_ProtocolMeta):
doc = typing.Protocol. doc
slots = ()

_is_protocol = True
_is_runtime_protocol = False

def init_subclass (cls, *args, **kwargs):


super(). init_subclass (*args, **kwargs)

# Determine if this is a protocol or a concrete


subclass. if not cls. dict .get('_is_protocol',
False):
cls._is_protocol = any(b is Protocol for b in cls. bases )

# Set (or override) the protocol subclass hook.


if ' subclasshook ' not in cls. dict :
cls. subclasshook = _proto_hook

# Prohibit instantiation for protocol classes


if cls._is_protocol and cls. init is Protocol. init :
cls. init = _no_init

else:
class Protocol(metaclass=_ProtocolMeta):
# There is quite a lot of overlapping code with typing.Generic.
# Unfortunately it is hard to avoid this on Python <3.8,
# as the typing module on Python 3.7 doesn't let us subclass typing.Generic!
"""Base class for protocol classes. Protocol classes are defined as::

class Proto(Protocol):
def meth(self) -> int:
...

Such classes are primarily used with static type checkers that recognize
110
structural subtyping (static duck-typing), for example::

111
class C:
def meth(self) -> int:
return 0

def func(x: Proto) -> int:


return x.meth()

func(C()) # Passes static type check

See PEP 544 for details. Protocol classes decorated with


@typing_extensions.runtime_checkable act
as simple-minded runtime-checkable protocols that check
only the presence of given attributes, ignoring their type signatures.

Protocol classes can be generic, they are defined as::

class GenProto(Protocol[T]):
def meth(self) -> T:
...
"""
slots = ()
_is_protocol = True
_is_runtime_protocol = False

def new (cls, *args,


**kwds): if cls is Protocol:
raise TypeError("Type Protocol cannot be instantiated; "
"it can only be used as a base class")
return super(). new (cls)

@typing._tp_cache
def class_getitem (cls, params):
if not isinstance(params, tuple):
params = (params,)
if not params and cls is not typing.Tuple:
raise TypeError(
f"Parameter list to {cls. qualname }[...] cannot be empty")
112
msg = "Parameters to generic types must be types."
params = tuple(typing._type_check(p, msg) for p in params)
if cls is Protocol:
# Generic can only be subscripted with unique type variables.
if not all(isinstance(p, typing.TypeVar) for p in params):
i=0
while isinstance(params[i], typing.TypeVar):
i += 1
raise TypeError(
"Parameters to Protocol[...] must all be type variables."

f" Parameter {i + 1} is {params[i]}")


if len(set(params)) != len(params):
raise TypeError(
"Parameters to Protocol[...] must all be unique")
else:
# Subscripting a regular Generic subclass.
_check_generic(cls, params, len(cls. parameters ))
return typing._GenericAlias(cls, params)

def init_subclass (cls, *args,


**kwargs): if ' orig_bases ' in cls.
dict :
error = typing.Generic in cls. orig_bases
else:
error = typing.Generic in cls. bases
if error:
raise TypeError("Cannot inherit from plain Generic")
_maybe_adjust_parameters(cls)

# Determine if this is a protocol or a concrete


subclass. if not cls. dict .get('_is_protocol',
None):
cls._is_protocol = any(b is Protocol for b in cls. bases )

# Set (or override) the protocol subclass hook.


if ' subclasshook ' not in cls. dict :
cls. subclasshook = _proto_hook

# Prohibit instantiation for protocol classes


113
if cls._is_protocol and cls. init is Protocol. init :
cls. init = _no_init

114
if sys.version_info >= (3, 8):
runtime_checkable = typing.runtime_checkable
else:
def runtime_checkable(cls):
"""Mark a protocol class as a runtime protocol, so that it
can be used with isinstance() and issubclass(). Raise
TypeError if applied to a non-protocol class.

This allows a simple-minded structural check very similar to


the one-offs in collections.abc such as Hashable.
"""
if not (
(isinstance(cls, _ProtocolMeta) or issubclass(cls, typing.Generic))
and getattr(cls, "_is_protocol", False)
):
raise TypeError('@runtime_checkable can be only applied to protocol
classes,'
f' got {cls!r}')
cls._is_runtime_protocol = True
return cls

# Exists for backwards compatibility.


runtime = runtime_checkable

# Our version of runtime-checkable protocols is faster on Python 3.7-3.11


if sys.version_info >= (3, 12):
SupportsInt = typing.SupportsInt
SupportsFloat = typing.SupportsFloat
SupportsComplex = typing.SupportsComplex
SupportsBytes = typing.SupportsBytes
SupportsIndex = typing.SupportsIndex
SupportsAbs = typing.SupportsAbs
SupportsRound = typing.SupportsRound
else:
115
@runtime_checkable
class SupportsInt(Protocol):
"""An ABC with one abstract method int ."""
slots = ()

@abc.abstractmethod
def int (self) -> int:
pass

@runtime_checkable
class SupportsFloat(Protocol):
"""An ABC with one abstract method float ."""

slots = ()

@abc.abstractmethod
def float (self) -> float:
pass

@runtime_checkable
class SupportsComplex(Protocol):
"""An ABC with one abstract method complex ."""
slots = ()

@abc.abstractmethod
def complex (self) -> complex:
pass

@runtime_checkable
class SupportsBytes(Protocol):
"""An ABC with one abstract method bytes ."""
slots = ()

@abc.abstractmethod
def bytes (self) -> bytes:
pass

@runtime_checkable
class SupportsIndex(Protocol):
slots = ()
116
@abc.abstractmethod
def index (self) -> int:
pass

@runtime_checkable
class SupportsAbs(Protocol[T_co]):
"""
An ABC with one abstract method abs that is covariant in its return type.
"""
slots = ()

@abc.abstractmethod
def abs (self) -> T_co:
pass

@runtime_checkable
class SupportsRound(Protocol[T_co]):
"""
An ABC with one abstract method round that is covariant in its return type.
"""
slots = ()

@abc.abstractmethod
def round (self, ndigits: int = 0) -> T_co:
pass

def _ensure_subclassable(mro_entries):
def inner(func):
if sys.implementation.name == "pypy" and sys.version_info < (3, 9):
cls_dict = {
" call ": staticmethod(func),
" mro_entries ": staticmethod(mro_entries)
}
t = type(func. name , (), cls_dict)
return functools.update_wrapper(t(), func)
else:
117
func. mro_entries = mro_entries
return func
return inner

if sys.version_info >= (3, 13):


# The standard library TypedDict in Python 3.8 does not store runtime
information # about which (if any) keys are optional. See
https://bugs.python.org/issue38834 # The standard library TypedDict in Python
3.9.0/1 does not honour the "total"
# keyword with old-style TypedDict(). See https://bugs.python.org/issue42059
# The standard library TypedDict below Python 3.11 does not store runtime
# information about optional and required keys when using Required or

NotRequired.
# Generic TypedDicts are also impossible using typing.TypedDict on Python
<3.11.
# Aaaand on 3.12 we add orig_bases to TypedDict
# to enable better runtime introspection.
# On 3.13 we deprecate some odd ways of creating TypedDicts.
TypedDict = typing.TypedDict
_TypedDictMeta = typing._TypedDictMeta
is_typeddict = typing.is_typeddict
else:
# 3.10.0 and later
_TAKES_MODULE = "module" in
inspect.signature(typing._type_check).parameters

if sys.version_info >= (3, 8):


_fake_name = "Protocol"
else:
_fake_name = "_Protocol"

class _TypedDictMeta(type):
def new (cls, name, bases, ns,
total=True): """Create new typed dict class
object.

This method is called when TypedDict is subclassed,


118
or when TypedDict is instantiated. This way
TypedDict supports all three syntax forms described in its docstring.

119
Subclasses and instances of TypedDict return actual dictionaries.
"""
for base in bases:
if type(base) is not _TypedDictMeta and base is not typing.Generic:
raise TypeError('cannot inherit from both a TypedDict type '
'and a non-TypedDict base class')

if any(issubclass(b, typing.Generic) for b in bases):


generic_base = (typing.Generic,)
else:
generic_base = ()

# typing.py generally doesn't let you inherit from plain Generic, unless
# the name of the class happens to be "Protocol" (or "_Protocol" on 3.7).
tp_dict = type. new (_TypedDictMeta, _fake_name, (*generic_base,
ns) dict),

tp_dict. name = name


if tp_dict. qualname == _fake_name:
tp_dict. qualname = name

if not hasattr(tp_dict, ' orig_bases '):


tp_dict. orig_bases = bases

annotations = {}
own_annotations = ns.get(' annotations ', {})
msg = "TypedDict('Name', {f0: t0, f1: t1, ...}); each t must be a type"
if _TAKES_MODULE:
own_annotations = {
n: typing._type_check(tp, msg, module=tp_dict. module )
for n, tp in own_annotations.items()
}
else:
own_annotations = {
n: typing._type_check(tp, msg)
for n, tp in own_annotations.items()
}
120
required_keys = set()

121
optional_keys = set()

for base in bases:


annotations.update(base. dict .get(' annotations ', {}))
required_keys.update(base. dict .get(' required_keys ', ()))
optional_keys.update(base. dict .get(' optional_keys ', ()))

annotations.update(own_annotations)
for annotation_key, annotation_type in own_annotations.items():
annotation_origin = get_origin(annotation_type)
if annotation_origin is Annotated:
annotation_args = get_args(annotation_type)
if annotation_args:
annotation_type = annotation_args[0]
annotation_origin = get_origin(annotation_type)

if annotation_origin is Required:
required_keys.add(annotation_key)
elif annotation_origin is NotRequired:
optional_keys.add(annotation_key)
elif total:
required_keys.add(annotation_key)
else:
optional_keys.add(annotation_key)

tp_dict. annotations = annotations


tp_dict. required_keys = frozenset(required_keys)
tp_dict. optional_keys = frozenset(optional_keys)
if not hasattr(tp_dict, ' total '):
tp_dict. total = total
return tp_dict

call = dict # static method

def subclasscheck (cls, other):


# Typed dicts are only for static structural subtyping.
raise TypeError('TypedDict does not support instance and class checks')

instancecheck = subclasscheck

122
_TypedDict = type. new (_TypedDictMeta, 'TypedDict', (), {})

@_ensure_subclassable(lambda bases: (_TypedDict,))


def TypedDict( typename, fields=_marker, *, total=True, **kwargs):
"""A simple typed namespace. At runtime it is equivalent to a plain
dict.

TypedDict creates a dictionary type such that a type checker will expect all
instances to have a certain set of keys, where each key is
associated with a value of a consistent type. This expectation
is not checked at runtime.

Usage::

class Point2D(TypedDict):
x: int
y: int
label: str

a: Point2D = {'x': 1, 'y': 2, 'label': 'good'} # OK


b: Point2D = {'z': 3, 'label': 'bad'} # Fails type check

assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first')

The type info can be accessed via the Point2D. annotations dict, and
the Point2D. required_keys and Point2D. optional_keys frozensets.
TypedDict supports an additional equivalent form::

Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str})

By default, all keys must be present in a TypedDict. It is possible


to override this by specifying totality::

class Point2D(TypedDict,
total=False): x: int
y: int

This means that a Point2D TypedDict can have any of the keys omitted. A type
checker is only expected to support a literal False or True as the value of
the total argument. True is the default, and makes all items defined in the
class body be required.
123
The Required and NotRequired special forms can also be used to mark
individual keys as being required or not required::

class Point2D(TypedDict):
x: int # the "x" key must always be present (Required is the default)
y: NotRequired[int] # the "y" key can be omitted

See PEP 655 for more details on Required and NotRequired.


"""
if fields is _marker or fields is None:
if fields is _marker:
deprecated_thing = "Failing to pass a value for the 'fields' parameter"
else:
deprecated_thing = "Passing `None` as the 'fields' parameter"

example = f"`{ typename} = TypedDict({ typename!r}, {{}})`"


deprecation_msg = (

f"{deprecated_thing} is deprecated and will be disallowed in "


"Python 3.15. To create a TypedDict class with 0 fields "
"using the functional syntax, pass an empty dictionary, e.g. "
) + example + "."
warnings.warn(deprecation_msg, DeprecationWarning, stacklevel=2)
fields =
kwargs elif kwargs:
raise TypeError("TypedDict takes either a dict or keyword
arguments," " but not both")
if kwargs:
warnings.warn(
"The kwargs-based syntax for TypedDict definitions is deprecated "
"in Python 3.11, will be removed in Python 3.13, and may not be "
"understood by third-party type checkers.",
DeprecationWarning,
stacklevel=2,
)

ns = {' annotations ': dict( fields)}


module = _caller()
if module is not None:
# Setting correct module is necessary to make typed dict classes pickleable.
124
ns[' module '] = module

td = _TypedDictMeta( typename, (), ns, total=total)


td. orig_bases = (TypedDict,)
return td

if hasattr(typing, "_TypedDictMeta"):
_TYPEDDICT_TYPES = (typing._TypedDictMeta,
_TypedDictMeta) else:
_TYPEDDICT_TYPES = (_TypedDictMeta,)

def is_typeddict(tp):
"""Check if an annotation is a TypedDict class

For example::
class Film(TypedDict):
title: str
year: int

is_typeddict(Film) # => True


is_typeddict(Union[list, str]) # => False
"""
# On 3.8, this would otherwise return True
if hasattr(typing, "TypedDict") and tp is typing.TypedDict:
return False
return isinstance(tp, _TYPEDDICT_TYPES)

if hasattr(typing, "assert_type"):
assert_type = typing.assert_type

else:
def assert_type( val, typ):
"""Assert (to the type checker) that the value is of the given type.

When the type checker encounters a call to assert_type(), it


emits an error if the value is not of the specified type::

def greet(name: str) -> None:


assert_type(name, str) # ok
125
assert_type(name, int) # type checker error

At runtime this returns the first argument unchanged and otherwise


does nothing.
"""
return val

if hasattr(typing, "Required"):
get_type_hints = typing.get_type_hints
else:
# replaces _strip_annotations()
def _strip_extras(t):
"""Strips Annotated, Required and NotRequired from a given type."""
if isinstance(t, _AnnotatedAlias):
return _strip_extras(t. origin )
if hasattr(t, " origin ") and t. origin in (Required, NotRequired):
return _strip_extras(t. args [0])
if isinstance(t, typing._GenericAlias):
stripped_args = tuple(_strip_extras(a) for a in t. args )
if stripped_args == t. args :
return t
return t.copy_with(stripped_args)
if hasattr(_types, "GenericAlias") and isinstance(t,
_types.GenericAlias): stripped_args = tuple(_strip_extras(a) for a in t.
args )
if stripped_args == t. args :
return t
return _types.GenericAlias(t. origin , stripped_args)
if hasattr(_types, "UnionType") and isinstance(t,
_types.UnionType): stripped_args = tuple(_strip_extras(a) for a in
t. args )
if stripped_args == t. args :
return t
return functools.reduce(operator.or_,

stripped_args) return t

def get_type_hints(obj, globalns=None, localns=None, include_extras=False):


"""Return type hints for an object.

126
This is often the same as obj. annotations , but it handles
forward references encoded as string literals, adds Optional[t] if
a

127
default value equal to None is set and recursively replaces all
'Annotated[T, ...]', 'Required[T]' or 'NotRequired[T]' with 'T'
(unless 'include_extras=True').

The argument may be a module, class, method, or function. The annotations


are returned as a dictionary. For classes, annotations include also
inherited members.

TypeError is raised if the argument is not of a type that can contain


annotations, and an empty dictionary is returned if no annotations are
present.

BEWARE -- the behavior of globalns and localns is counterintuitive


(unless you are familiar with how eval() and exec() work). The
search order is locals first, then globals.

- If no dict arguments are passed, an attempt is made to use the


globals from obj (or the respective module's globals for classes),
and these are also used as the locals. If the object does not appear
to have globals, an empty dictionary is used.

- If one dict argument is passed, it is used for both globals


and locals.

- If two dict arguments are passed, they specify globals and


locals, respectively.
"""
if hasattr(typing, "Annotated"):
hint = typing.get_type_hints(
obj, globalns=globalns, localns=localns, include_extras=True
)
else:
hint = typing.get_type_hints(obj, globalns=globalns, localns=localns)
if include_extras:
return hint
return {k: _strip_extras(t) for k, t in hint.items()}

# Python 3.9+ has PEP 593 (Annotated)


if hasattr(typing, 'Annotated'):
128
Annotated = typing.Annotated
# Not exported and not a public API, but needed for get_origin() and
get_args() # to work.
_AnnotatedAlias = typing._AnnotatedAlias
# 3.7-3.8
else:
class _AnnotatedAlias(typing._GenericAlias, _root=True):
"""Runtime representation of an annotated type.

At its core 'Annotated[t, dec1, dec2, ...]' is an alias for the type 't'
with extra annotations. The alias behaves like a normal typing alias,
instantiating is the same as instantiating the underlying type, binding
it to types is also the same.
"""
def init (self, origin, metadata):
if isinstance(origin, _AnnotatedAlias):
metadata = origin. metadata + metadata
origin = origin. origin
super(). init (origin, origin)
self. metadata = metadata

def copy_with(self, params):


assert len(params) == 1
new_type = params[0]
return _AnnotatedAlias(new_type, self. metadata )

def repr (self):


return (f"typing_extensions.Annotated[{typing._type_repr(self. origin )},
"
f"{', '.join(repr(a) for a in self. metadata )}]")

def reduce (self):


return operator.getitem,
(
Annotated, (self. origin ,) + self. metadata
)

def eq (self, other):

129
if not isinstance(other, _AnnotatedAlias):
return NotImplemented

130
if self. origin != other. origin :
return False
return self. metadata == other. metadata

def hash (self):


return hash((self. origin , self. metadata ))

class Annotated:
"""Add context specific metadata to a type.

Example: Annotated[int, runtime_check.Unsigned] indicates to the


hypothetical runtime_check module that this type is an unsigned int.
Every other consumer of this type can ignore this metadata and treat
this type as int.

The first argument to Annotated must be a valid type (and will be


in the origin field), the remaining arguments are kept as a tuple
in the extra field.

Details:

- It's an error to call `Annotated` with less than two arguments.


- Nested Annotated are flattened::

Annotated[Annotated[T, Ann1, Ann2], Ann3] == Annotated[T, Ann1, Ann2,


Ann3]

- Instantiating an annotated type is equivalent to instantiating


the underlying type::

Annotated[C, Ann1](5) == C(5)

- Annotated can be used as a generic type alias::

Optimized = Annotated[T, runtime.Optimize()]


Optimized[int] == Annotated[int, runtime.Optimize()]

OptimizedList = Annotated[List[T], runtime.Optimize()]


131
OptimizedList[int] == Annotated[List[int], runtime.Optimize()]
"""

slots = ()

def new (cls, *args, **kwargs):


raise TypeError("Type Annotated cannot be instantiated.")

@typing._tp_cache
def class_getitem (cls, params):
if not isinstance(params, tuple) or len(params) < 2:
raise TypeError("Annotated[...] should be used "
"with at least two arguments (a type and an "
"annotation).")
allowed_special_forms = (ClassVar, Final)
if get_origin(params[0]) in allowed_special_forms:
origin = params[0]
else:
msg = "Annotated[t, ...]: t must be a type."
origin = typing._type_check(params[0], msg)
metadata = tuple(params[1:])
return _AnnotatedAlias(origin, metadata)

def init_subclass (cls, *args,


**kwargs): raise TypeError(
f"Cannot subclass {cls. module }.Annotated"
)

# Python 3.8 has get_origin() and get_args() but those implementations aren't
# Annotated-aware, so we can't use those. Python 3.9's versions don't support
# ParamSpecArgs and ParamSpecKwargs, so only Python 3.10's versions will do.
if sys.version_info[:2] >= (3, 10):
get_origin = typing.get_origin
get_args = typing.get_args
# 3.7-3.9
else:
try:
# 3.9+
from typing import _BaseGenericAlias
132
except ImportError:
_BaseGenericAlias = typing._GenericAlias
try:
# 3.9+
from typing import GenericAlias as _typing_GenericAlias
except ImportError:
_typing_GenericAlias = typing._GenericAlias

def get_origin(tp):
"""Get the unsubscripted version of a type.

This supports generic types, Callable, Tuple, Union, Literal, Final, ClassVar
and Annotated. Return None for unsupported types. Examples::

get_origin(Literal[42]) is Literal
get_origin(int) is None
get_origin(ClassVar[int]) is ClassVar
get_origin(Generic) is Generic
get_origin(Generic[T]) is Generic
get_origin(Union[T, int]) is Union
get_origin(List[Tuple[T, T]][int]) == list
get_origin(P.args) is P
"""

if isinstance(tp, _AnnotatedAlias):
return Annotated
if isinstance(tp, (typing._GenericAlias, _typing_GenericAlias,
_BaseGenericAlias,
ParamSpecArgs, ParamSpecKwargs)):
return tp. origin
if tp is typing.Generic:
return typing.Generic
return None

def get_args(tp):
"""Get type arguments with all substitutions performed.

For unions, basic simplifications used by Union constructor are performed.


Examples::
133
get_args(Dict[str, int]) == (str, int)
get_args(int) == ()
get_args(Union[int, Union[T, int], str][int]) == (int, str)
get_args(Union[int, Tuple[T, int]][str]) == (int, Tuple[str, int])
get_args(Callable[[], T][int]) == ([], int)
"""
if isinstance(tp, _AnnotatedAlias):
return (tp. origin ,) + tp. metadata
if isinstance(tp, (typing._GenericAlias, _typing_GenericAlias)):
if getattr(tp, "_special", False):
return ()
res = tp. args
if get_origin(tp) is collections.abc.Callable and res[0] is not Ellipsis:
res = (list(res[:-1]), res[-1])
return res
return ()

# 3.10+
if hasattr(typing, 'TypeAlias'):
TypeAlias = typing.TypeAlias
# 3.9
elif sys.version_info[:2] >= (3, 9):
@_ExtensionsSpecialForm
def TypeAlias(self, parameters):

"""Special marker indicating that an assignment should


be recognized as a proper type alias definition by type
checkers.

For example::

Predicate: TypeAlias = Callable[..., bool]

It's invalid when used anywhere except as in the example above.


"""
raise TypeError(f"{self} is not subscriptable")
# 3.7-3.8
else:
TypeAlias = _ExtensionsSpecialForm(
134
'TypeAlias',
doc="""Special marker indicating that an assignment should
be recognized as a proper type alias definition by type
checkers.

For example::

Predicate: TypeAlias = Callable[..., bool]

It's invalid when used anywhere except as in the example


above."""
)

def _set_default(type_param, default):


if isinstance(default, (tuple, list)):
type_param. default = tuple((typing._type_check(d, "Default must be a
type")
for d in default))
elif default != _marker:
type_param. default = typing._type_check(default, "Default must be a
type")
else:
type_param. default = None

def _set_module(typevarlike):
# for pickling:
def_mod = _caller(depth=3)
if def_mod != 'typing_extensions':
typevarlike. module = def_mod

class _DefaultMixin:
"""Mixin for TypeVarLike defaults."""

slots = ()
init = _set_default

135
# Classes using this metaclass must provide a _backported_typevarlike ClassVar
class _TypeVarLikeMeta(type):
def instancecheck (cls, instance: Any) -> bool:
return isinstance( instance, cls._backported_typevarlike)

# Add default and infer_variance parameters from PEP 696 and 695
class TypeVar(metaclass=_TypeVarLikeMeta):
"""Type variable."""

_backported_typevarlike = typing.TypeVar

def new (cls, name, *constraints, bound=None,


covariant=False, contravariant=False,
default=_marker, infer_variance=False):
if hasattr(typing, "TypeAliasType"):
# PEP 695 implemented, can pass infer_variance to typing.TypeVar
typevar = typing.TypeVar(name, *constraints, bound=bound,
covariant=covariant, contravariant=contravariant,
infer_variance=infer_variance)
else:
typevar = typing.TypeVar(name, *constraints, bound=bound,
covariant=covariant, contravariant=contravariant)
if infer_variance and (covariant or contravariant):
raise ValueError("Variance cannot be specified with
infer_variance.") typevar. infer_variance = infer_variance

_set_default(typevar, default)
_set_module(typevar)
return typevar

def init_subclass (cls) -> None:


raise TypeError(f"type '{ name }.TypeVar' is not an acceptable base type")

# Python 3.10+ has PEP 612


if hasattr(typing, 'ParamSpecArgs'):
ParamSpecArgs = typing.ParamSpecArgs
ParamSpecKwargs =
136
typing.ParamSpecKwargs

137
# 3.7-3.9
else:
class _Immutable:
"""Mixin to indicate that object should not be copied."""
slots = ()

def copy (self):


return self

def deepcopy (self, memo):


return self

class ParamSpecArgs(_Immutable):
"""The args for a ParamSpec object.

Given a ParamSpec object P, P.args is an instance of

ParamSpecArgs. ParamSpecArgs objects have a reference back to

their ParamSpec: P.args. origin is P

This type is meant for runtime introspection and has no special meaning to
static type checkers.
"""
def init (self, origin):
self. origin = origin

def repr (self):


return f"{self. origin . name }.args"

def eq (self, other):


if not isinstance(other, ParamSpecArgs):
return NotImplemented
return self. origin == other. origin

class ParamSpecKwargs(_Immutable):
"""The kwargs for a ParamSpec object.

138
Given a ParamSpec object P, P.kwargs is an instance of

ParamSpecKwargs. ParamSpecKwargs objects have a reference back to

their ParamSpec: P.kwargs. origin is P

This type is meant for runtime introspection and has no special meaning to
static type checkers.
"""
def init (self, origin):
self. origin = origin

def repr (self):


return f"{self. origin . name }.kwargs"

def eq (self, other):


if not isinstance(other, ParamSpecKwargs):
return NotImplemented
return self. origin == other. origin

# 3.10+
if hasattr(typing, 'ParamSpec'):

# Add default parameter - PEP 696


class ParamSpec(metaclass=_TypeVarLikeMeta):
"""Parameter specification."""

_backported_typevarlike = typing.ParamSpec

def new (cls, name, *, bound=None,


covariant=False, contravariant=False,
infer_variance=False,
default=_marker):
if hasattr(typing, "TypeAliasType"):
# PEP 695 implemented, can pass infer_variance to typing.TypeVar
paramspec = typing.ParamSpec(name, bound=bound,
covariant=covariant,
contravariant=contravariant,
infer_variance=infer_variance)
139
else:

140
paramspec = typing.ParamSpec(name, bound=bound,
covariant=covariant,
contravariant=contravariant)
paramspec. infer_variance = infer_variance

_set_default(paramspec, default)
_set_module(paramspec)
return paramspec

def init_subclass (cls) -> None:


raise TypeError(f"type '{ name }.ParamSpec' is not an acceptable base
type")

# 3.7-3.9
else:

# Inherits from list as a workaround for Callable checks in Python < 3.9.2.
class ParamSpec(list, _DefaultMixin):
"""Parameter specification variable.

Usage::

P = ParamSpec('P')

Parameter specification variables exist primarily for the benefit of static


type checkers. They are used to forward the parameter types of one
callable to another callable, a pattern commonly found in higher order
functions and decorators. They are only valid when used in ``Concatenate``,
or s the first argument to ``Callable``.

In Python 3.10 and higher,


they are also supported in user-defined Generics at runtime.
See class Generic for more information on generic types. An
example for annotating a decorator::

T = TypeVar('T')
P = ParamSpec('P')

def add_logging(f: Callable[P, T]) -> Callable[P, T]:


141
'''A type-safe decorator to add logging to a function.'''
def inner(*args: P.args, **kwargs: P.kwargs) -> T:
logging.info(f'{f. name } was called')
return f(*args, **kwargs)
return inner

@add_logging
def add_two(x: float, y: float) -> float:
'''Add two numbers together.'''
return x + y

Parameter specification variables defined with covariant=True or


contravariant=True can be used to declare covariant or contravariant
generic types. These keyword arguments are valid, but their actual semantics
are yet to be decided. See PEP 612 for details.

Parameter specification variables can be introspected.

e.g.: P. name == 'T'


P. bound == None
P. covariant == False
P. contravariant == False

Note that only parameter specification variables defined in global scope can
be pickled.
"""

# Trick Generic parameters .


class = typing.TypeVar

@property
def args(self):
return ParamSpecArgs(self)

@property
def kwargs(self):
return ParamSpecKwargs(self)

142
def init (self, name, *, bound=None, covariant=False,
contravariant=False, infer_variance=False, default=_marker):
super(). init ([self])
self. name = name
self. covariant = bool(covariant)
self. contravariant = bool(contravariant)
self. infer_variance = bool(infer_variance)
if bound:
self. bound = typing._type_check(bound, 'Bound must be a type.')
else:
self. bound = None
_DefaultMixin. init (self, default)

# for pickling:
def_mod = _caller()
if def_mod != 'typing_extensions':
self. module = def_mod

def repr (self):


if self. infer_variance :
prefix = ''
elif self. covariant :
prefix = '+'
elif self. contravariant :
prefix = '-'
else:
prefix = '~'
return prefix + self. name

def hash (self):


return object. hash (self)

def eq (self, other):


return self is other

def reduce (self):


return self. name

# Hack to get typing._type_check to pass.


143
def call (self, *args,
**kwargs): pass

# 3.7-3.9
if not hasattr(typing, 'Concatenate'):
# Inherits from list as a workaround for Callable checks in Python < 3.9.2.
class _ConcatenateGenericAlias(list):

# Trick Generic into looking into this for parameters .


class = typing._GenericAlias

# Flag in 3.8.
_special = False

def init (self, origin,


args): super(). init
(args)
self. origin = origin
self. args = args

def repr (self):


_type_repr = typing._type_repr
return (f'{_type_repr(self. origin )}'
f'[{", ".join(_type_repr(arg) for arg in self. args )}]')

def hash (self):


return hash((self. origin , self. args ))

# Hack to get typing._type_check to pass in


Generic. def call (self, *args, **kwargs):
pass

@property
def parameters (self):
return tuple(
tp for tp in self. args if isinstance(tp, (typing.TypeVar, ParamSpec))
)
144
# 3.7-3.9
@typing._tp_cache
def _concatenate_getitem(self, parameters):
if parameters == ():
raise TypeError("Cannot take a Concatenate of no types.")
if not isinstance(parameters, tuple):
parameters = (parameters,)
if not isinstance(parameters[-1], ParamSpec):
raise TypeError("The last parameter to Concatenate should be a "
"ParamSpec variable.")
msg = "Concatenate[arg, ...]: each arg must be a type."
parameters = tuple(typing._type_check(p, msg) for p in parameters)
return _ConcatenateGenericAlias(self, parameters)

# 3.10+
if hasattr(typing, 'Concatenate'):
Concatenate = typing.Concatenate
_ConcatenateGenericAlias = typing._ConcatenateGenericAlias # noqa: F811
# 3.9
elif sys.version_info[:2] >= (3, 9):
@_ExtensionsSpecialForm
def Concatenate(self, parameters):
"""Used in conjunction with ``ParamSpec`` and ``Callable`` to represent a
higher order function which adds, removes or transforms parameters of a
callable.

For example::

Callable[Concatenate[int, P], int]

See PEP 612 for detailed information.


"""

return _concatenate_getitem(self, parameters)


# 3.7-8
else:
class _ConcatenateForm(_ExtensionsSpecialForm,
_root=True): def getitem (self, parameters):
145
return _concatenate_getitem(self, parameters)

Concatenate = _ConcatenateForm(
'Concatenate',
doc="""Used in conjunction with ``ParamSpec`` and ``Callable`` to represent a
higher order function which adds, removes or transforms parameters of a
callable.

For example::

Callable[Concatenate[int, P], int]

See PEP 612 for detailed information.


""")

# 3.10+
if hasattr(typing, 'TypeGuard'):
TypeGuard = typing.TypeGuard
# 3.9
elif sys.version_info[:2] >= (3, 9):
@_ExtensionsSpecialForm
def TypeGuard(self, parameters):
"""Special typing form used to annotate the return type of a user-defined
type guard function. ``TypeGuard`` only accepts a single type argument.
At runtime, functions marked this way should return a boolean.

``TypeGuard`` aims to benefit *type narrowing* -- a technique used by


static type checkers to determine a more precise type of an expression within
a program's code flow. Usually type narrowing is done by analyzing
conditional code flow and applying the narrowing to a block of code. The
conditional expression here is sometimes referred to as a "type guard".

Sometimes it would be convenient to use a user-defined boolean function


as a type guard. Such a function should use ``TypeGuard[...]`` as its
return type to alert static type checkers to this intention.

Using ``-> TypeGuard`` tells the static type checker that for a given
function:

1. The return value is a boolean.


146
2. If the return value is ``True``, the type of its
argument is the type inside ``TypeGuard``.

For example::

def is_str(val: Union[str, float]):


# "isinstance" type guard
if isinstance(val, str):
# Type of ``val`` is narrowed to ``str``
...
else:
# Else, type of ``val`` is narrowed to ``float``.
...

Strict type narrowing is not enforced -- ``TypeB`` need not be a


narrower form of ``TypeA`` (it can even be a wider form) and this may
lead to type-unsafe results. The main reason is to allow for things like
narrowing ``List[object]`` to ``List[str]`` even though the latter is not
a subtype of the former, since ``List`` is invariant. The responsibility of
writing type-safe type guards is left to the user.

``TypeGuard`` also works with type variables. For more information, see
PEP 647 (User-Defined Type Guards).
"""
item = typing._type_check(parameters, f'{self} accepts only a single type.')
return typing._GenericAlias(self, (item,))
# 3.7-3.8
else:
class _TypeGuardForm(_ExtensionsSpecialForm, _root=True):
def getitem (self, parameters):
item = typing._type_check(parameters,
f'{self._name} accepts only a single type')
return typing._GenericAlias(self, (item,))

TypeGuard =
_TypeGuardForm( 'TypeGuard',

doc="""Special typing form used to annotate the return type of a user-defined


type guard function. ``TypeGuard`` only accepts a single type argument.
At runtime, functions marked this way should return a boolean.
147
``TypeGuard`` aims to benefit *type narrowing* -- a technique used by
static type checkers to determine a more precise type of an expression within
a program's code flow. Usually type narrowing is done by analyzing
conditional code flow and applying the narrowing to a block of code. The
conditional expression here is sometimes referred to as a "type guard".

Sometimes it would be convenient to use a user-defined boolean function


as a type guard. Such a function should use ``TypeGuard[...]`` as its
return type to alert static type checkers to this intention.

Using ``-> TypeGuard`` tells the static type checker that for a given
function:

1. The return value is a boolean.


2. If the return value is ``True``, the type of its
argument is the type inside ``TypeGuard``.

For example::

def is_str(val: Union[str, float]):


# "isinstance" type guard
if isinstance(val, str):
# Type of ``val`` is narrowed to ``str``
...
else:
# Else, type of ``val`` is narrowed to ``float``.
...

Strict type narrowing is not enforced -- ``TypeB`` need not be a


narrower form of ``TypeA`` (it can even be a wider form) and this may
lead to type-unsafe results. The main reason is to allow for things like
narrowing ``List[object]`` to ``List[str]`` even though the latter is not
a subtype of the former, since ``List`` is invariant. The responsibility of
writing type-safe type guards is left to the user.

``TypeGuard`` also works with type variables. For more information, see
PEP 647 (User-Defined Type Guards).
148
""")

# Vendored from cpython typing._SpecialFrom


class _SpecialForm(typing._Final,
_root=True):
slots = ('_name', ' doc ', '_getitem')

def init (self, getitem):


self._getitem = getitem
self._name = getitem. name
self. doc = getitem. doc

def getattr (self, item):


if item in {' name ', ' qualname '}:
return self._name

raise AttributeError(item)

def mro_entries (self, bases):


raise TypeError(f"Cannot subclass {self!r}")

def repr (self):


return f'typing_extensions.{self._name}'

def reduce (self):


return self._name

def call (self, *args, **kwds):


raise TypeError(f"Cannot instantiate {self!r}")

def or (self, other):


return typing.Union[self, other]

def ror (self, other):


return typing.Union[other,

self] def

instancecheck (self, obj):

149
raise TypeError(f"{self} cannot be used with isinstance()")

150
def subclasscheck (self, cls):
raise TypeError(f"{self} cannot be used with issubclass()")

@typing._tp_cache
def getitem (self, parameters):
return self._getitem(self,
parameters)

if hasattr(typing, "LiteralString"):
LiteralString = typing.LiteralString
else:
@_SpecialForm
def LiteralString(self, params):
"""Represents an arbitrary literal string.

Example::

from typing_extensions import LiteralString

def query(sql: LiteralString) -> ...:


...

query("SELECT * FROM table") # ok


query(f"SELECT * FROM {input()}") # not ok

See PEP 675 for details.

"""
raise TypeError(f"{self} is not subscriptable")

if hasattr(typing, "Self"):
Self = typing.Self
else:
@_SpecialForm
def Self(self, params):
"""Used to spell the type of "self" in classes.

151
Example::

from typing import Self

class ReturnsSelf:
def parse(self, data: bytes) -> Self:
...
return self

"""

raise TypeError(f"{self} is not subscriptable")

if hasattr(typing, "Never"):
Never = typing.Never
else:
@_SpecialForm
def Never(self, params):
"""The bottom type, a type that has no members.

This can be used to define a function that should never be


called, or a function that never returns::

from typing_extensions import Never

def never_call_me(arg: Never) ->

None:
pass

def int_or_str(arg: int | str) -> None:


never_call_me(arg) # type checker error
match arg:
case int():
print("It's an int")
case str():
print("It's a str")
case _:
never_call_me(arg) # ok, arg is of type Never

152
"""

raise TypeError(f"{self} is not subscriptable")

if hasattr(typing, 'Required'):
Required = typing.Required
NotRequired =
typing.NotRequired
elif sys.version_info[:2] >= (3, 9):
@_ExtensionsSpecialForm
def Required(self, parameters):
"""A special typing construct to mark a key of a total=False TypedDict
as required. For example:

class Movie(TypedDict,
total=False): title: Required[str]
year: int

m = Movie(
title='The Matrix', # typechecker error if key is omitted
year=1999,
)

There is no runtime checking that a required key is actually provided


when instantiating a related TypedDict.
"""
item = typing._type_check(parameters, f'{self._name} accepts only a single
type.')
return typing._GenericAlias(self, (item,))

@_ExtensionsSpecialForm
def NotRequired(self, parameters):
"""A special typing construct to mark a key of a TypedDict as
potentially missing. For example:

class Movie(TypedDict):
title: str
year: NotRequired[int]

153
m = Movie(
title='The Matrix', # typechecker error if key is omitted
year=1999,
)
"""
item = typing._type_check(parameters, f'{self._name} accepts only a single
type.')
return typing._GenericAlias(self, (item,))

else:
class _RequiredForm(_ExtensionsSpecialForm,
_root=True): def getitem (self, parameters):
item = typing._type_check(parameters,
f'{self._name} accepts only a single type.')
return typing._GenericAlias(self, (item,))

Required = _RequiredForm(
'Required',
doc="""A special typing construct to mark a key of a total=False TypedDict
as required. For example:

class Movie(TypedDict,
total=False): title: Required[str]
year: int

m = Movie(
title='The Matrix', # typechecker error if key is omitted
year=1999,
)

There is no runtime checking that a required key is actually provided


when instantiating a related TypedDict.
""")
NotRequired = _RequiredForm(
'NotRequired',
doc="""A special typing construct to mark a key of a TypedDict as
potentially missing. For example:

class Movie(TypedDict):
154
title: str
year: NotRequired[int]

m = Movie(
title='The Matrix', # typechecker error if key is omitted
year=1999,
)
""")

_UNPACK_DOC = """\
Type unpack operator.

The type unpack operator takes the child types from some container type,
such as `tuple[int, str]` or a `TypeVarTuple`, and 'pulls them out'. For
example:

# For some generic class `Foo`:


Foo[Unpack[tuple[int, str]]] # Equivalent to Foo[int, str]

Ts = TypeVarTuple('Ts')
# Specifies that `Bar` is generic in an arbitrary number of types.
# (Think of `Ts` as a tuple of an arbitrary number of individual
# `TypeVar`s, which the `Unpack` is 'pulling out' directly into
the # `Generic[]`.)
class Bar(Generic[Unpack[Ts]]):
... Bar[int] # Valid
Bar[int, str] # Also valid

From Python 3.11, this can also be done using the `*` operator:

Foo[*tuple[int, str]]
class Bar(Generic[*Ts]): ...

The operator can also be used along with a `TypedDict` to annotate


`**kwargs` in a function signature. For instance:

class Movie(TypedDict):
155
name: str
year: int

# This function expects two keyword arguments - *name* of type `str` and
# *year* of type `int`.
def foo(**kwargs: Unpack[Movie]): ...

Note that there is only some runtime checking of this operator. Not
everything the runtime allows may be accepted by static type checkers.

For more information, see PEP 646 and PEP 692.


"""

if sys.version_info >= (3, 12): # PEP 692 changed the repr of Unpack[]
Unpack = typing.Unpack

def _is_unpack(obj):
return get_origin(obj) is Unpack

elif sys.version_info[:2] >= (3, 9):


class _UnpackSpecialForm(_ExtensionsSpecialForm,
_root=True): def init (self, getitem):
super(). init (getitem)
self. doc = _UNPACK_DOC

class _UnpackAlias(typing._GenericAlias, _root=True):


class = typing.TypeVar

@_UnpackSpecialForm
def Unpack(self, parameters):
item = typing._type_check(parameters, f'{self._name} accepts only a single
type.')
return _UnpackAlias(self, (item,))

def _is_unpack(obj):
return isinstance(obj, _UnpackAlias)

else:
class _UnpackAlias(typing._GenericAlias, _root=True):
156
class = typing.TypeVar

class _UnpackForm(_ExtensionsSpecialForm, _root=True):

def getitem (self, parameters):


item = typing._type_check(parameters,
f'{self._name} accepts only a single type.')
return _UnpackAlias(self, (item,))

Unpack = _UnpackForm('Unpack', doc=_UNPACK_DOC)

def _is_unpack(obj):
return isinstance(obj, _UnpackAlias)

if hasattr(typing, "TypeVarTuple"): # 3.11+

# Add default parameter - PEP 696


class TypeVarTuple(metaclass=_TypeVarLikeMeta):
"""Type variable tuple."""

_backported_typevarlike = typing.TypeVarTuple

def new (cls, name, *, default=_marker):


tvt = typing.TypeVarTuple(name)
_set_default(tvt, default)
_set_module(tvt)
return tvt

def init_subclass (self, *args, **kwds):


raise TypeError("Cannot subclass special typing classes")

else:
class TypeVarTuple(_DefaultMixin):
"""Type variable tuple.

Usage::

Ts = TypeVarTuple('Ts')

157
In the same way that a normal type variable is a stand-in for a single
type such as ``int``, a type variable *tuple* is a stand-in for a *tuple*
type such as ``Tuple[int, str]``.

Type variable tuples can be used in ``Generic`` declarations.


Consider the following example::

class Array(Generic[*Ts]): ...

The ``Ts`` type variable tuple here behaves like ``tuple[T1, T2]``,
where ``T1`` and ``T2`` are type variables. To use these type variables
as type parameters of ``Array``, we must *unpack* the type variable tuple using
the star operator: ``*Ts``. The signature of ``Array`` then behaves
as if we had simply written ``class Array(Generic[T1, T2]): ...``.
In contrast to ``Generic[T1, T2]``, however, ``Generic[*Shape]`` allows
us to parameterise the class with an *arbitrary* number of type parameters.

Type variable tuples can be used anywhere a normal ``TypeVar`` can.


This includes class definitions, as shown above, as well as function
signatures and variable annotations::

class Array(Generic[*Ts]):

def init (self, shape: Tuple[*Ts]):


self._shape: Tuple[*Ts] = shape

def get_shape(self) -> Tuple[*Ts]:


return self._shape

shape = (Height(480), Width(640))


x: Array[Height, Width] = Array(shape)
y = abs(x) # Inferred type is Array[Height, Width]
z=x+x # ... is Array[Height, Width]
x.get_shape() # ... is tuple[Height,
Width]

"""

# Trick Generic parameters .


158
class = typing.TypeVar

159
def iter (self):
yield self. unpacked

def init (self, name, *, default=_marker):

self. name = name


_DefaultMixin. init (self, default)

# for pickling:
def_mod = _caller()
if def_mod != 'typing_extensions':
self. module = def_mod

self. unpacked = Unpack[self]

def repr (self):


return self. name

def hash (self):


return object. hash (self)

def eq (self, other):


return self is other

def reduce (self):


return self. name

def init_subclass (self, *args,


**kwds): if '_root' not in kwds:
raise TypeError("Cannot subclass special typing classes")

if hasattr(typing, "reveal_type"):
reveal_type = typing.reveal_type
else:
def reveal_type( obj: T) -> T:
"""Reveal the inferred type of a variable.

When a static type checker encounters a call to ``reveal_type()``,


160
it will emit the inferred type of the argument::

x: int = 1
reveal_type(x)

Running a static type checker (e.g., ``mypy``) on this example


will produce output similar to 'Revealed type is "builtins.int"'.

At runtime, the function prints the runtime type of the


argument and returns it unchanged.

"""
print(f"Runtime type is {type( obj). name !r}", file=sys.stderr)
return obj

if hasattr(typing, "assert_never"):
assert_never = typing.assert_never
else:
def assert_never( arg: Never) -> Never:
"""Assert to the type checker that a line of code is unreachable.

Example::

def int_or_str(arg: int | str) -> None:


match arg:
case int():
print("It's an int")
case str():
print("It's a str")
case _:
assert_never(arg)

If a type checker finds that a call to assert_never() is


reachable, it will emit an error.

At runtime, this throws an exception when called.

"""
raise AssertionError("Expected code to be unreachable")

161
if sys.version_info >= (3, 12):
# dataclass_transform exists in 3.11 but lacks the frozen_default parameter
dataclass_transform = typing.dataclass_transform
else:
def dataclass_transform(
*,

eq_default: bool = True,


order_default: bool = False,
kw_only_default: bool = False,
frozen_default: bool = False,
field_specifiers: typing.Tuple[
typing.Union[typing.Type[typing.Any], typing.Callable[..., typing.Any]],
...
] = (),
**kwargs: typing.Any,
) -> typing.Callable[[T], T]:
"""Decorator that marks a function, class, or metaclass as
providing dataclass-like behavior.

Example:

from typing_extensions import dataclass_transform

_T = TypeVar("_T")

# Used on a decorator function


@dataclass_transform()
def create_model(cls: type[_T]) -> type[_T]:
...
return cls

@create_model
class CustomerModel:
id: int
name: str

# Used on a base class


@dataclass_transform()
162
class ModelBase: ...

class CustomerModel(ModelBase):
id: int
name: str

# Used on a metaclass
@dataclass_transform()
class ModelMeta(type): ...

class ModelBase(metaclass=ModelMeta): ...

class CustomerModel(ModelBase):
id: int
name: str

Each of the ``CustomerModel`` classes defined in this example will now


behave similarly to a dataclass created with the
``@dataclasses.dataclass`` decorator. For example, the type checker will
synthesize an `` init ``
method.

The arguments to this decorator can be used to customize this behavior:


- ``eq_default`` indicates whether the ``eq`` parameter is assumed to be
True or False if it is omitted by the caller.
- ``order_default`` indicates whether the ``order`` parameter is
assumed to be True or False if it is omitted by the caller.
- ``kw_only_default`` indicates whether the ``kw_only`` parameter is
assumed to be True or False if it is omitted by the caller.
- ``frozen_default`` indicates whether the ``frozen`` parameter is
assumed to be True or False if it is omitted by the caller.
- ``field_specifiers`` specifies a static list of supported classes
or functions that describe fields, similar to ``dataclasses.field()``.

At runtime, this decorator records its arguments in the


`` dataclass_transform `` attribute on the decorated object.

See PEP 681 for details.

"""
def decorator(cls_or_fn):
163
cls_or_fn. dataclass_transform ={

164
"eq_default": eq_default,
"order_default": order_default,
"kw_only_default": kw_only_default,
"frozen_default": frozen_default,
"field_specifiers": field_specifiers,
"kwargs": kwargs,
}
return cls_or_fn
return decorator

if hasattr(typing, "override"):
override = typing.override
else:
_F = typing.TypeVar("_F", bound=typing.Callable[..., typing.Any])

def override( arg: _F) -> _F:


"""Indicate that a method is intended to override a method in a base class.

Usage:

class Base:
def method(self) -> None: ...
pass

class Child(Base):
@override
def method(self) -> None:
super().method()

When this decorator is applied to a method, the type checker will


validate that it overrides a method with the same name on a base class.
This helps prevent bugs that may occur when a base class is changed
without an equivalent change to a child class.

There is no runtime checking of these properties. The decorator


sets the `` override `` attribute to ``True`` on the decorated
object to allow runtime introspection.

See PEP 698 for details.

165
"""
try:
arg. override = True
except (AttributeError, TypeError):
# Skip the attribute silently if it is not writable.
# AttributeError happens if the object has slots or a
# read-only property, TypeError if it's a builtin class.
pass
return arg

if hasattr(typing, "deprecated"):
deprecated = typing.deprecated
else:
_T = typing.TypeVar("_T")

def deprecated(
msg: str,
*,
category: typing.Optional[typing.Type[Warning]] = DeprecationWarning,
stacklevel: int = 1,
) -> typing.Callable[[_T], _T]:
"""Indicate that a class, function or overload is deprecated.

Usage:

@deprecated("Use B instead")
class A:
pass

@deprecated("Use g instead")
def f():
pass

@overload
@deprecated("int support is deprecated")
def g(x: int) -> int: ...
@overload
def g(x: str) -> int: ...

166
When this decorator is applied to an object, the type checker
will generate a diagnostic on usage of the deprecated object.

The warning specified by ``category`` will be emitted on use


of deprecated objects. For functions, that happens on calls;
for classes, on instantiation. If the ``category`` is ``None``,
no warning is emitted. The ``stacklevel`` determines where the
warning is emitted. If it is ``1`` (the default), the warning
is emitted at the direct caller of the deprecated object; if it
is higher, it is emitted further up the stack.

The decorator sets the `` deprecated ``


attribute on the decorated object to the deprecation message
passed to the decorator. If applied to an overload, the
decorator must be after the ``@overload`` decorator for the
attribute to exist on the overload as returned by
``get_overloads()``.

See PEP 702 for details.

"""
def decorator( arg: _T) ->
_T: if category is None:
arg. deprecated = msg
return arg
elif isinstance( arg, type):
original_new = arg. new
has_init = arg. init is not object. init

@functools.wraps(original_new)
def new (cls, *args, **kwargs):
warnings.warn( msg, category=category, stacklevel=stacklevel + 1)
if original_new is not object. new :
return original_new(cls, *args, **kwargs)
# Mirrors a similar check in object. new .
elif not has_init and (args or kwargs):
raise TypeError(f"{cls. name }() takes no arguments")
else:
return original_new(cls)
167
arg. new = staticmethod( new )
arg. deprecated = new . deprecated = msg
return arg
elif callable( arg):
@functools.wraps( arg)
def wrapper(*args, **kwargs):
warnings.warn( msg, category=category, stacklevel=stacklevel +
1) return arg(*args, **kwargs)

arg. deprecated = wrapper. deprecated = msg


return wrapper
else:

raise TypeError(
"@deprecated decorator with non-None category must be applied to
" f"a class or callable, not { arg!r}"
)

return decorator

# We have to do some monkey patching to deal with the dual nature


of # Unpack/TypeVarTuple:
# - We want Unpack to be a kind of TypeVar so it gets accepted
in # Generic[Unpack[Ts]]
# - We want it to *not* be treated as a TypeVar for the purposes of
# counting generic parameters, so that when we subscript a generic,
# the runtime doesn't try to substitute the Unpack with the subscripted
type. if not hasattr(typing, "TypeVarTuple"):
typing._collect_type_vars = _collect_type_vars
typing._check_generic = _check_generic

# Backport typing.NamedTuple as it exists in Python 3.12.


# In 3.11, the ability to define generic `NamedTuple`s was supported.
# This was explicitly disallowed in 3.9-3.10, and only half-worked in
<=3.8. # On 3.12, we added orig_bases to call-based
NamedTuples
# On 3.13, we deprecated kwargs-based
NamedTuples if sys.version_info >= (3, 13):
168
NamedTuple = typing.NamedTuple

169
else:
def _make_nmtuple(name, types, module, defaults=()):
fields = [n for n, t in types]
annotations = {n: typing._type_check(t, f"field {n} annotation must be a type")
for n, t in types}
nm_tpl = collections.namedtuple(name, fields,
defaults=defaults, module=module)
nm_tpl. annotations = nm_tpl. new . annotations = annotations
# The `_field_types` attribute was removed in 3.9;
# in earlier versions, it is the same as the ` annotations ` attribute
if sys.version_info < (3, 9):
nm_tpl._field_types = annotations
return nm_tpl

_prohibited_namedtuple_fields = typing._prohibited
_special_namedtuple_fields = frozenset({' module ', ' name ',
' annotations '})

class _NamedTupleMeta(type):
def new (cls, typename, bases, ns):
assert _NamedTuple in bases
for base in bases:
if base is not _NamedTuple and base is not typing.Generic:
raise TypeError(
'can only inherit from a NamedTuple type and Generic')
bases = tuple(tuple if base is _NamedTuple else base for base in
bases) types = ns.get(' annotations ', {})
default_names = []
for field_name in types:
if field_name in ns:
default_names.append(field_name)
elif default_names:
raise TypeError(f"Non-default namedtuple field {field_name} "
f"cannot follow default field"
f"{'s' if len(default_names) > 1 else ''} "
f"{', '.join(default_names)}")
nm_tpl = _make_nmtuple(
typename, types.items(),
defaults=[ns[n] for n in default_names],
module=ns[' module ']
170
)
nm_tpl. bases = bases
if typing.Generic in bases:
if hasattr(typing, '_generic_class_getitem'): # 3.12+
nm_tpl. class_getitem =
classmethod(typing._generic_class_getitem)
else:
class_getitem = typing.Generic. class_getitem . func
nm_tpl. class_getitem = classmethod(class_getitem)
# update from user namespace without overriding special namedtuple
attributes
for key in ns:
if key in _prohibited_namedtuple_fields:
raise AttributeError("Cannot overwrite NamedTuple attribute " + key)

elif key not in _special_namedtuple_fields and key not in nm_tpl._fields:


setattr(nm_tpl, key, ns[key])
if typing.Generic in bases:
nm_tpl. init_subclass ()
return nm_tpl

_NamedTuple = type. new (_NamedTupleMeta, 'NamedTuple', (),

{}) def _namedtuple_mro_entries(bases):


assert NamedTuple in bases
return (_NamedTuple,)

@_ensure_subclassable(_namedtuple_mro_entries)
def NamedTuple( typename, fields=_marker, **kwargs):
"""Typed version of namedtuple.

Usage::

class Employee(NamedTuple):
name: str
id: int

This is equivalent to::

Employee = collections.namedtuple('Employee', ['name', 'id'])


171
The resulting class has an extra annotations attribute, giving a
dict that maps field names to types. (The field names are also in
the _fields attribute, which is part of the namedtuple API.)
An alternative equivalent functional syntax is also accepted::

Employee = NamedTuple('Employee', [('name', str), ('id', int)])


"""
if fields is _marker:
if kwargs:
deprecated_thing = "Creating NamedTuple classes using keyword
arguments"
deprecation_msg = (
"{name} is deprecated and will be disallowed in Python {remove}. "
"Use the class-based or functional syntax instead."
)

else:
deprecated_thing = "Failing to pass a value for the 'fields'
parameter" example = f"`{ typename} =
NamedTuple({ typename!r}, [])`" deprecation_msg = (
"{name} is deprecated and will be disallowed in Python {remove}. "
"To create a NamedTuple class with 0 fields "
"using the functional syntax, "
"pass an empty list, e.g. "
) + example + "."
elif fields is None:
if kwargs:
raise TypeError(
"Cannot pass `None` as the 'fields' parameter "
"and also specify fields using keyword arguments"
)
else:
deprecated_thing = "Passing `None` as the 'fields' parameter"
example = f"`{ typename} = NamedTuple({ typename!r}, [])`"
deprecation_msg = (
"{name} is deprecated and will be disallowed in Python {remove}. "
"To create a NamedTuple class with 0 fields "
"using the functional syntax, "
"pass an empty list, e.g. "
) + example + "."
172
elif kwargs:
raise TypeError("Either list of fields or keywords"
" can be provided to NamedTuple, not
both") if fields is _marker or fields is
None:
warnings.warn(
deprecation_msg.format(name=deprecated_thing, remove="3.15"),
DeprecationWarning,
stacklevel=2,
)
fields = kwargs.items()
nt = _make_nmtuple( typename, fields, module=_caller())
nt. orig_bases = (NamedTuple,)
return nt

# On 3.8+, alter the signature so that it matches typing.NamedTuple.


# The signature of typing.NamedTuple on >=3.8 is invalid syntax in Python 3.7,

# so just leave the signature as it is on 3.7.


if sys.version_info >= (3, 8):
_new_signature = '(typename, fields=None, /, **kwargs)'
if isinstance(NamedTuple, _types.FunctionType):
NamedTuple. text_signature = _new_signature
else:
NamedTuple. call . text_signature = _new_signature

if hasattr(collections.abc, "Buffer"):
Buffer = collections.abc.Buffer
else:
class Buffer(abc.ABC):
"""Base class for classes that implement the buffer protocol.

The buffer protocol allows Python objects to expose a low-


level memory buffer interface. Before Python 3.12, it is not
possible to implement the buffer protocol in pure Python code,
or even to check whether a class implements the buffer
protocol. In
Python 3.12 and higher, the `` buffer `` method allows access
to the buffer protocol from Python code, and the
173
``collections.abc.Buffer`` ABC allows checking whether a class
implements the buffer protocol.

174
To indicate support for the buffer protocol in earlier versions,
inherit from this ABC, either in a stub file or at runtime,
or use ABC registration. This ABC provides no methods, because
there is no Python-accessible methods shared by pre-3.12 buffer
classes. It is useful primarily for static checks.

"""

# As a courtesy, register the most common stdlib buffer classes.


Buffer.register(memoryview)
Buffer.register(bytearray)
Buffer.register(bytes)

# Backport of types.get_original_bases, available on 3.12+ in


CPython if hasattr(_types, "get_original_bases"):

get_original_bases = _types.get_original_bases
else:
def get_original_bases( cls):
"""Return the class's "original" bases prior to modification by
` mro_entries `.

Examples::

from typing import TypeVar, Generic


from typing_extensions import NamedTuple, TypedDict

T = TypeVar("T")
class Foo(Generic[T]): ...
class Bar(Foo[int], float): ...
class Baz(list[str]): ...
Eggs = NamedTuple("Eggs", [("a", int), ("b", str)])
Spam = TypedDict("Spam", {"a": int, "b": str})

assert get_original_bases(Bar) == (Foo[int], float)


assert get_original_bases(Baz) == (list[str],)
assert get_original_bases(Eggs) == (NamedTuple,)
assert get_original_bases(Spam) == (TypedDict,)
175
assert get_original_bases(int) == (object,)
"""
try:
return cls. orig_bases
except AttributeError:
try:
return cls. bases
except AttributeError:
raise TypeError(
f'Expected an instance of type, not {type( cls). name !r}'
) from None

# NewType is a class on Python 3.10+, making it pickleable


# The error message for subclassing instances of NewType was improved on
3.11+ if sys.version_info >= (3, 11):
NewType = typing.NewType

else:
class NewType:
"""NewType creates simple unique types with almost zero
runtime overhead. NewType(name, tp) is considered a subtype of tp
by static type checkers. At runtime, NewType(name, tp) returns
a dummy callable that simply returns its argument. Usage::
UserId = NewType('UserId', int)
def name_by_id(user_id: UserId) -> str:
...
UserId('user') # Fails type check
name_by_id(42) # Fails type check
name_by_id(UserId(42)) # OK
num = UserId(5) + 1 # type: int
"""

def call (self, obj):


return obj

def init (self, name, tp):


self. qualname = name
if '.' in name:
176
name = name.rpartition('.')[-1]
self. name = name
self. supertype = tp
def_mod = _caller()
if def_mod != 'typing_extensions':
self. module = def_mod

def mro_entries (self, bases):


# We defined mro_entries to get a better error message
# if a user attempts to subclass a NewType instance. bpo-
46170 supercls_name = self. name

class Dummy:
def init_subclass (cls):
subcls_name = cls. name
raise TypeError(
f"Cannot subclass an instance of NewType. "
f"Perhaps you were looking for: "
f"`{subcls_name} = NewType({subcls_name!r}, {supercls_name})`"
)

return (Dummy,)

def repr (self):


return f'{self. module }.{self. qualname }'

def reduce (self):


return self. qualname

if sys.version_info >= (3, 10):


# PEP 604 methods
# It doesn't make sense to have these methods on Python <3.10

def or (self, other):


return typing.Union[self, other]

def ror (self, other):


return typing.Union[other, self]

if hasattr(typing, "TypeAliasType"):
177
TypeAliasType = typing.TypeAliasType
else:
def _is_unionable(obj):
"""Corresponds to is_unionable() in unionobject.c in CPython."""
return obj is None or isinstance(obj, (
type,
_types.GenericAlias,
_types.UnionType,
TypeAliasType,
))

class TypeAliasType:
"""Create named, parameterized type aliases.

This provides a backport of the new `type` statement in Python 3.12:

type ListOrSet[T] = list[T] | set[T]

is equivalent to:

T = TypeVar("T")
ListOrSet = TypeAliasType("ListOrSet", list[T] | set[T], type_params=(T,))

The name ListOrSet can then be used as an alias for the type it refers to.

The type_params argument should contain all the type parameters used
in the value of the type alias. If the alias is not generic, this
argument is omitted.

Static type checkers should only support type aliases declared using
TypeAliasType that follow these rules:

- The first argument (the name) must be a string literal.


- The TypeAliasType instance must be immediately assigned to a variable
of the same name. (For example, 'X = TypeAliasType("Y", int)' is
invalid, as is 'X, Y = TypeAliasType("X", int), TypeAliasType("Y",
int)').

"""
178
def init (self, name: str, value, *,
type_params=()): if not isinstance(name, str):
raise TypeError("TypeAliasType name must be a
string") self. value = value
self. type_params = type_params

parameters = []
for type_param in type_params:
if isinstance(type_param, TypeVarTuple):
parameters.extend(type_param)
else:
parameters.append(type_param)
self. parameters = tuple(parameters)
def_mod = _caller()
if def_mod != 'typing_extensions':
self. module = def_mod
# Setting this attribute closes the TypeAliasType from further
modification self. name = name

def setattr (self, name: str, value: object) -> None:


if hasattr(self, " name "):

self._raise_attribute_error( name)
super(). setattr ( name, value)

def delattr (self, name: str) -> Never:


self._raise_attribute_error( name)

def _raise_attribute_error(self, name: str) -> Never:


# Match the Python 3.12 error messages exactly
if name == " name ":
raise AttributeError("readonly attribute")
elif name in {" value ", " type_params ", " parameters ",
" module "}:
raise AttributeError(
f"attribute '{name}' of 'typing.TypeAliasType' objects
" "is not writable"
)
else:
raise AttributeError(
179
f"'typing.TypeAliasType' object has no attribute '{name}'"
)

def repr (self) -> str:


return self. name

def getitem (self, parameters):


if not isinstance(parameters, tuple):
parameters = (parameters,)
parameters = [
typing._type_check(
item, f'Subscripting {self. name } requires a type.'
)
for item in parameters
]
return typing._GenericAlias(self, tuple(parameters))

def reduce (self):


return self. name

def init_subclass (cls, *args,


**kwargs): raise TypeError(
"type 'typing_extensions.TypeAliasType' is not an acceptable base type"
)

# The presence of this method convinces typing._type_check


# that TypeAliasTypes are types.
def call (self):
raise TypeError("Type alias is not callable")

if sys.version_info >= (3, 10):


def or (self, right):
# For forward compatibility with 3.12, reject Unions
# that are not accepted by the built-in Union.
if not _is_unionable(right):
return NotImplemented
return typing.Union[self, right]
180
def ror (self, left):
if not _is_unionable(left):
return NotImplemented
return typing.Union[left, self]

if hasattr(typing, "is_protocol"):
is_protocol = typing.is_protocol
get_protocol_members = typing.get_protocol_members
else:
def is_protocol( tp: type) -> bool:
"""Return True if the given type is a Protocol.

Example::

>>> from typing_extensions import Protocol, is_protocol


>>> class P(Protocol):
... def a(self) -> str: ...
... b: int
>>> is_protocol(P)
True

>>> is_protocol(int)
False
"""
return (
isinstance( tp, type)
and getattr( tp, '_is_protocol', False)
and tp is not Protocol
and tp is not getattr(typing, "Protocol", object())
)

def get_protocol_members( tp: type) -> typing.FrozenSet[str]:


"""Return the set of members defined in a Protocol.

Example::

>>> from typing_extensions import Protocol, get_protocol_members


181
>>> class P(Protocol):
... def a(self) -> str: ...
... b: int
>>> get_protocol_members(P)
frozenset({'a', 'b'})

Raise a TypeError for arguments that are not


Protocols. """
if not is_protocol( tp):
raise TypeError(f'{ tp!r} is not a Protocol')
if hasattr( tp, ' protocol_attrs '):
return frozenset( tp. protocol_attrs )
return frozenset(_get_protocol_attrs( tp))

# Aliases for items that have always been in typing.


# Explicitly assign these (rather than using `from typing import *` at the top),
# so that we get a CI error if one of these is deleted from typing.py
# in a future version of Python
AbstractSet = typing.AbstractSet
AnyStr = typing.AnyStr
BinaryIO = typing.BinaryIO
Callable = typing.Callable

Collection = typing.Collection
Container = typing.Container
Dict = typing.Dict
ForwardRef = typing.ForwardRef
FrozenSet = typing.FrozenSet
Generator = typing.Generator
Generic = typing.Generic
Hashable = typing.Hashable
IO = typing.IO
ItemsView = typing.ItemsView
Iterable = typing.Iterable
Iterator = typing.Iterator
KeysView = typing.KeysView
List = typing.List
Mapping = typing.Mapping
182
MappingView = typing.MappingView
Match = typing.Match
MutableMapping = typing.MutableMapping
MutableSequence = typing.MutableSequence
MutableSet = typing.MutableSet
Optional = typing.Optional
Pattern = typing.Pattern
Reversible = typing.Reversible
Sequence = typing.Sequence
Set = typing.Set
Sized = typing.Sized
TextIO = typing.TextIO
Tuple = typing.Tuple
Union = typing.Union
ValuesView = typing.ValuesView
cast = typing.cast
no_type_check = typing.no_type_check
no_type_check_decorator = typing.no_type_check_decorator

183
5) Testing
5.1) Test Strategy/ Test Case

Developing a robust test strategy for DevSearch involves ensuring that


all aspects of the platform, including its modules and features, are
thoroughly tested to deliver a high-quality user experience. Here's a
detailed test strategy for DevSearch:

1. Requirement Analysis:
- Understand the functional and non-functional requirements of DevSearch.
- Analyze user stories, use cases, and acceptance criteria to define
test scenarios.

2. Test Planning:
- Define testing objectives, scope, and timelines.
- Allocate resources, including testing environments, tools, and team members.
- Determine testing techniques and methodologies, such as manual
testing, automated testing, and exploratory testing.

3. Test Environment Setup:


- Set up testing environments that replicate the production
environment, including servers, databases, and network configurations.
- Ensure that test environments are isolated from production to prevent
any impact on live users.

4. Test Case Design:


- Create comprehensive test cases covering functional, non-functional, and
edge cases.
- Include positive and negative test scenarios to validate expected behavior
and error handling.
- Define test data and inputs required for executing test cases.

184
5. Functional Testing:
- Conduct functional testing to verify that all features and modules
of DevSearch work as intended.
- Test search functionality, user authentication, profile management,
documentation access, community interaction, and recommendation
engine.
- Verify integration with external tools and platforms for
seamless interoperability.

6. Usability Testing:
- Evaluate the user interface, navigation flow, and overall user experience
of DevSearch.
- Test accessibility, responsiveness, and compatibility across different
devices and browsers.
- Gather feedback from real users to identify usability issues and areas
for improvement.

7. Performance Testing:
- Perform load testing, stress testing, and scalability testing to assess
the performance of DevSearch under various conditions.
- Measure response times, throughput, and resource utilization to
identify performance bottlenecks.
- Optimize system architecture and configurations to ensure
optimal performance and responsiveness.

8. Security Testing:
- Conduct security testing to identify vulnerabilities and ensure data protection.
- Test authentication mechanisms, authorization controls, data encryption,
and secure communication protocols.
- Perform penetration testing and vulnerability scanning to uncover
potential security risks.

185
9. Compatibility Testing:
- Verify compatibility with different operating systems, browsers, and devices.
- Test DevSearch on various platforms to ensure consistent functionality
and user experience across different environments.

10. Regression Testing:


- Implement regression testing to validate that new updates or fixes do
not introduce regressions or break existing functionality.
- Automate regression test cases to streamline the testing process and
ensure consistent test coverage.

11. Monitoring and Reporting:


- Monitor test execution progress and collect metrics on test coverage,
defect density, and test effectiveness.
- Generate test reports summarizing test results, findings, and
recommendations for stakeholders.
- Communicate testing progress and any identified risks or issues to
the development team and project stakeholders.

12. Feedback and Iteration:


- Gather feedback from users and stakeholders based on testing results and
user acceptance.
- Iterate on the development of DevSearch, addressing identified issues,
implementing enhancements, and continuously improving the platform based
on user feedback.

By following this comprehensive test strategy, DevSearch can ensure the


reliability, performance, security, and usability of its platform, delivering a
seamless experience for developers worldwide.

186
6) Future Enhancement

- Certainly! Here are some potential future enhancements for


DevSearch:

1. Advanced Search Filters:


Implement more advanced search filters to allow users to refine their
search results by factors such as programming language version, release
date, popularity, and community rating.

2. Interactive Tutorials:
Integrate interactive tutorials and coding exercises directly into
DevSearch to provide hands-on learning experiences for users, helping
them learn new technologies more effectively.

3. Real-time Collaboration: Enable real-time collaboration


features, such as live coding sessions, pair programming, and code
reviews, to facilitate teamwork and knowledge sharing among
developers.

4. Integration with Learning Platforms: Partner with online


learning platforms and MOOCs (Massive Open Online Courses) to
integrate educational content directly into DevSearch, allowing users
to seamlessly access tutorials, courses, and certification programs.

5. Code Playground: Create a code playground within DevSearch


where users can experiment with code snippets, test algorithms,
and prototype ideas without leaving the platform.

6. Personalized Learning Paths: Implement personalized learning


paths based on users' skill levels, interests, and learning goals,
providing curated recommendations and resources to help users
progress in their programming journey.

187
7. Code Analysis and Debugging Tools: Integrate code analysis
tools and debugging utilities into DevSearch to help developers
identify and fix issues in their code more efficiently.

8. Machine Learning-Powered Recommendations: Utilize


machine learning algorithms to improve the accuracy of content
recommendations, leveraging user behavior data and contextual
information to suggest relevant resources and topics.

9. Offline Access: Develop offline access capabilities, allowing users


to download documentation, tutorials, and other resources for offline
viewing and reference, enhancing accessibility and convenience.

10. Community Events and Workshops: Host virtual community


events, workshops, and webinars directly within DevSearch, providing
opportunities for developers to network, learn from industry experts,
and collaborate on projects.

11. Internationalization and Localization: Expand support for


multiple languages and regions to make DevSearch more accessible to
developers worldwide, including localized content, interfaces, and
community forums.

12. Accessibility Features: Improve accessibility features within


DevSearch to ensure that the platform is usable by all users,
including those with disabilities, by adhering to accessibility
standards and guidelines.

13. Blockchain Integration for Trust and Transparency: Explore


the integration of blockchain technology to enhance trust and
transparency within the developer community, such as verifying the
authenticity of code snippets, tutorials, and credentials.

These enhancements can help elevate DevSearch into a more


comprehensive and valuable platform for developers, offering a wide
range of tools, resources, and collaborative features to support their
188
learning and productivity needs.

7) Screenshot:-

Home page

189
Profile page

190
Message page

191
Project page

192
About the page

193
Login page

194
195
8) Bibliography
Online Resources:

TensorFlow Documentation:
https://www.tensorflow.org/ OpenCV Documentation:
https://docs.opencv.org/

GitHub Repositories:

GitHub - OpenCV: https://github.com/opencv/opencv

GitHub - TensorFlow:

https://github.com/tensorflow/tensorflow Tutorials and

196

You might also like