diff --git a/Jobs_Collections/.DS_Store b/Jobs_Collections/.DS_Store deleted file mode 100644 index f2c9d21..0000000 Binary files a/Jobs_Collections/.DS_Store and /dev/null differ diff --git a/Jobs_Collections/.gitattributes b/Jobs_Collections/.gitattributes deleted file mode 100644 index dfe0770..0000000 --- a/Jobs_Collections/.gitattributes +++ /dev/null @@ -1,2 +0,0 @@ -# Auto detect text files and perform LF normalization -* text=auto diff --git a/Jobs_Collections/README.md b/Jobs_Collections/README.md deleted file mode 100644 index 03fed58..0000000 --- a/Jobs_Collections/README.md +++ /dev/null @@ -1,66 +0,0 @@ - - -1. 프로젝트 설명 - - 취준생들을 위하여 모든 채용 포탈의 정보를 해당 사이트 하나만으로 쉽게 검색할 수 있게 합니다. - -2. 프로젝트 생김새 - - -3. 개발해야 하는 기능(우선순위) - - html 전체적인 생김새 - - - 뉴스 크롤링 - - 사람인 크롤링 - - 잡코리아 크롤링 - - 인디드 크롤링 - - - Flask -> 뉴스, 사람인, 잡코리아, 인디드 - - - 검색 (검색어, 포탈, 위치, 근무 형태) JS - - - Like list 생김새 html - - Like JS - - - - -4. 다음 시간까지 해야하는 Todo list - - 검색 (검색어, 포탈, 위치, 근무 형태) JS 구현 - - 검색한 데이터를 크롤링해서 flask로 가져오는 기능 구현 - - Like list 생김새 html 구현 - - -###################################################################################### - -2. 프로젝트 설명 - - 취준생들을 위하여 모든 채용 포탈의 정보를 해당 사이트 하나만으로 쉽게 검색할 수 있게 합니다. - - -3. 기능 - - 사람인, 잡코리아, 인디드 세개의 채용포탈사이트에서 검색한 정보를 즉시 크롤링하여 웹페이지에 띄워줍니다. - - 찜 기능을 구현하여 저장하기 위해 Local storage를 사용하여 저장하고 불러올 수 있게 만들었습니다. - -4. 어려움 - - 각 포탈에서 크롤링한 데이터를 text로만 불러올때, 불필요한 태그들로 인해 오류가 발생했었지만, 정규 표현식 re.sub를 사용하여 불필요한 문자를 다른것으로 치환하여 해결하였습니다. - - 삭제 기능을 구현할때 선택한 값만 Local storage에서 지우는것에서 문제가 발생했지만, event.target 이벤트가 일어날 타겟을 지정하여 그 객체의 li값을 삭제함으로써 해결하였습니다. - - Python으로 크롤링한 데이터를 HTML로 가져오는 것에서 어려움을 느꼈으나, flask와 Ajax를 사용하여 해결하였습니다. - -5. 다음엔 - - 각 함수로 뉴스, 크롤링 등 여러가지 기능을 한번에 합칠때 힘들었지만, 해결된 기능이 잘 실행될때 즐거움을 느꼈습니다. - - 디자인 감각이 없어서 다음엔 팀 프로젝트로 프론트엔드 백엔드 나눠서 한번 진행해보고 싶습니다. - - - - - - - diff --git a/Jobs_Collections/__pycache__/indeed.cpython-38.pyc b/Jobs_Collections/__pycache__/indeed.cpython-38.pyc deleted file mode 100644 index ff504bb..0000000 Binary files a/Jobs_Collections/__pycache__/indeed.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/__pycache__/job_korea.cpython-38.pyc b/Jobs_Collections/__pycache__/job_korea.cpython-38.pyc deleted file mode 100644 index fa25160..0000000 Binary files a/Jobs_Collections/__pycache__/job_korea.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/__pycache__/news.cpython-38.pyc b/Jobs_Collections/__pycache__/news.cpython-38.pyc deleted file mode 100644 index e327374..0000000 Binary files a/Jobs_Collections/__pycache__/news.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/__pycache__/saramin.cpython-38.pyc b/Jobs_Collections/__pycache__/saramin.cpython-38.pyc deleted file mode 100644 index 88e8115..0000000 Binary files a/Jobs_Collections/__pycache__/saramin.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/indeed.py b/Jobs_Collections/indeed.py deleted file mode 100644 index cbba7ed..0000000 --- a/Jobs_Collections/indeed.py +++ /dev/null @@ -1,137 +0,0 @@ - -from bs4 import BeautifulSoup -import requests -import json -import re -from flask import Flask, render_template, jsonify, request - - -global URL -global LIMIT -LIMIT = 20 - - -def get_last_page(): - result = requests.get(URL) - - # 뷰티풀숩을 사용해 Html을 전체 가져온다. - soup = BeautifulSoup(result.text, 'html.parser') - - # page 수를 찾기 위해 해당 div를 가져와서 확인한다. - pagination = soup.find("div", {"class": "pagination"}) - - if pagination is not None: - - links = pagination.find_all('a') # 가져온것에서 페이지의 링크 수를 찾아온다. - pages = [] # 링크에서 span이 붙은것만 빼와서 리스트에 저장한다. 뒤에 짜잘한것을 없애주기 위해. - - # Operation spans[-1] 하면 맨 마지막것을 칭한다. So, [:-1]은 span을 가져오되 마지막 하나를 제외한다. - for link in links[:-1]: - # [0:5]하면 0부터 5까지 가져온다. - # pages.append(link.find("span")) - # pages.append(link.find("span").string) #1, 2> 에서 문자만 가져오기 위해 string 사용 - - # pages.append(link.string) #바로 위의 결과와 같게 나온다. 위에 것을 쉽게 만든것이다. 링크 안에는 많은 내용이 있지만 string은 단 1개이다. - pages.append(int(link.string)) # 위에것을 가져오면 문자열이기때문에 정수형으로 바꿔준다. - # print(page) - # Operation spans[-1] 하면 맨 마지막것을 칭한다. So, [:-1]은 span을 가져오되 마지막 하나를 제외한다. - # [0:5]하면 0부터 5까지 가져온다. - # print(pages) 최종적으로 가져온 페이지의 수는 2, 3, 4, 5 이렇게 정수형으로만 가져온다. - # 이렇게 하게되면 Page의 총 갯수를 불러오게 된다. - - # 1. 가장 마지막 페이지를 가져온다. - # print(pages[-1]) #마지막것 1개를 출력한다. - max_page = pages[-1] # 가장 마지막 페이지를 찾아 변수로 지정한다. - # print(range(max_page)) # range를 사용하여 0부터 maxpage까지 출력 - return max_page - else: - return 0 - - -def extract_job(html): - company_a = str(html.find("span", {"class": "company"})) - companys= re.sub('<.+?>', '', company_a, 0).strip() - - # if companys is not None: - # companys = companys - # else : - # companys_b = companys_a.find("b") - # companys = companys_a.string - # print(companys) - - - positions = html.find("a", {"data-tn-element": "jobTitle"})["title"] - locations_span = html.find( - "span", {"class": "location accessible-contrast-color-location"}) - if locations_span is not None: - locations = locations_span.string - else: - locations = '위치정보는 링크를 통해서 확인' - job_id = html["data-jk"] - # income_span = html.find("span", {"class": "salaryText"}) - # if income_span is not None: - # income = income_span.string.strip() - # else: - # income = '회사 내규에 따름' - links = f'https://kr.indeed.com/viewjob?jk={job_id}&tk=1e9t47m537los801&from=serp&vjs=3' - - - # return {'company': company, 'position': position, 'location': location, 'link': link, 'income': income} - return {'companys': companys, 'positions': positions, 'locations': locations, 'links': links } - -# wep page를 넘길때마다 start=0, 20, 40 넘어가는 규칙을 사용하기 위해 x20을 해준다. -def extracts_jobs(last_page): - id_jobs = [] - # for page in range(last_page): - for page in range(1): - print(f"Scrapping Indeed : Page : {page+1}") - # URL을 추가하고 page수와 LIMIT을 정하는 문자열을 연결시켜주었다. - #print(URL) - result = requests.get(f"{URL}&start={page*LIMIT}") - soup = BeautifulSoup(result.text, 'html.parser') - # print(soup) - results = soup.find_all("div", {"class": "jobsearch-SerpJobCard"}) - - for result in results: - job = extract_job(result) - id_jobs.append(job) - return id_jobs - - -def id_get_jobs(input_keyword_recieve, input_location_recieve, input_jobtype_recieve): - - - global URL - global LIMIT - LIMIT = 20 - - if input_location_recieve == '전체(희망 지역)': - input_location = '' - else: - input_location = input_location_recieve - - - if input_jobtype_recieve == '전체(근무 형태)': - input_jobtype = '' - elif input_jobtype_recieve == '정규직': - input_jobtype = 'fulltime' - elif input_jobtype_recieve == '계약직': - input_jobtype = 'contract' - elif input_jobtype_recieve == '인턴': - input_jobtype = 'internship' - elif input_jobtype_recieve == '아르바이트': - input_jobtype = 'parttime' - elif input_jobtype_recieve == '병역특례': - input_jobtype = 'custom_1' - - print("검색어는", input_keyword_recieve) - print("근무형태 입력은", input_jobtype) - print("위치 입력은", input_location) - - URL = f'https://kr.indeed.com/%EC%B7%A8%EC%97%85?q={input_keyword_recieve}&l={input_location}&jt={input_jobtype}&limit={LIMIT}&radius=25' - print(URL) - last_page = get_last_page() # 최대 페이지를 정의하는 함수를 변수에 넣는다. - id_jobs = extracts_jobs(last_page) #최대 페이지를 정의하는 함수를 넣은 변수를 인자로 넣고 함수를 실행한다. - - return id_jobs - # return jsonify ({'result':'success','id_jobs':id_jobs}) \ No newline at end of file diff --git a/Jobs_Collections/index.py b/Jobs_Collections/index.py deleted file mode 100644 index f8e4bea..0000000 --- a/Jobs_Collections/index.py +++ /dev/null @@ -1,89 +0,0 @@ - -from bs4 import BeautifulSoup -import requests -import json -from flask import Flask, render_template, jsonify, request - -from news import news_card -from indeed import id_get_jobs -from saramin import sa_get_jobs -from job_korea import jk_get_jobs - -app = Flask(__name__) - - -## HTML을 주는 부분 -@app.route('/') -def home(): - return render_template('Jobs_collection.html') - - -@app.route('/api/news', methods=['GET']) -def get_news(): - return news_card() - - -@app.route('/api/saramin', methods=['GET']) -def get_saramin_jobs(): - input_keyword_recieve = request.args.get('input_keyword_give') - input_location_recieve = request.args.get('input_location_give') - input_jobtype_recieve = request.args.get('input_jobtype_give') - # print(input_keyword_recieve) - # print(input_location_recieve) - # print(input_jobtype_recieve) - sa_jobs = sa_get_jobs(input_keyword_recieve, input_location_recieve, input_jobtype_recieve) - # return sa_get_jobs() - # return id_get_jobs() - return jsonify ({'result':'success','sa_jobs':sa_jobs}) - - - -@app.route('/api/indeed', methods=['GET']) -def get_indeed_jobs(): - input_keyword_recieve = request.args.get('input_keyword_give') - input_location_recieve = request.args.get('input_location_give') - input_jobtype_recieve = request.args.get('input_jobtype_give') - # print(input_keyword_recieve) - # print(input_location_recieve) - # print(input_jobtype_recieve) - id_jobs = id_get_jobs(input_keyword_recieve, input_location_recieve, input_jobtype_recieve) - # return sa_get_jobs() - # return id_get_jobs() - return jsonify ({'result':'success','id_jobs':id_jobs}) - - - -@app.route('/api/job_korea', methods=['GET']) -def get_job_korea_jobs(): - input_keyword_recieve = request.args.get('input_keyword_give') - input_location_recieve = request.args.get('input_location_give') - input_jobtype_recieve = request.args.get('input_jobtype_give') - # print(input_keyword_recieve) - # print(input_location_recieve) - # print(input_jobtype_recieve) - jk_jobs = jk_get_jobs(input_keyword_recieve, input_location_recieve, input_jobtype_recieve) - # return sa_get_jobs() - # return jk_get_jobs() - return jsonify ({'result':'success','jk_jobs':jk_jobs}) - -@app.route('/api/total', methods=['GET']) -def get_total_jobs(): - # return sa_get_jobs() - input_keyword_recieve = request.args.get('input_keyword_give') - input_location_recieve = request.args.get('input_location_give') - input_jobtype_recieve = request.args.get('input_jobtype_give') - print(input_keyword_recieve) - print(input_location_recieve) - print(input_jobtype_recieve) - jk_jobs = jk_get_jobs(input_keyword_recieve, input_location_recieve, input_jobtype_recieve) - sa_jobs = sa_get_jobs(input_keyword_recieve, input_location_recieve, input_jobtype_recieve) - id_jobs = id_get_jobs(input_keyword_recieve, input_location_recieve, input_jobtype_recieve) - # print(type(jk_jobs), jk_jobs) - # print(type(b)) - - return jsonify ({'result':'success','jk_jobs':jk_jobs, 'sa_jobs':sa_jobs, 'id_jobs':id_jobs}) - - -if __name__ == '__main__': - app.run('localhost', port=10038, debug=True) -# print(news_craw()) \ No newline at end of file diff --git a/Jobs_Collections/job_korea.py b/Jobs_Collections/job_korea.py deleted file mode 100644 index 95e2c8f..0000000 --- a/Jobs_Collections/job_korea.py +++ /dev/null @@ -1,128 +0,0 @@ -from bs4 import BeautifulSoup -import requests -import json -from flask import Flask, render_template, jsonify, request - -global job_type_box -job_type_box = '1' -global URL - - - -def get_last_page(): - result = requests.get(URL) - - # 뷰티풀숩을 사용해 Html을 전체 가져온다. - soup = BeautifulSoup(result.text, 'html.parser') - pagination = soup.find("div", {"class":"tplPagination newVer wide"}).find_all("li") - if pagination is not None: - last_page = pagination[-1].get_text() - return int(last_page) - else: - return 0 - -def extract_jobs(last_page): - jk_jobs = [] - # for page in range(last_page): - for page in range(1): - #for page in range(1): - print(f"Job-Koera page : {page+1}") - result = requests.get(URL+f'&Page_No={page}') - soup = BeautifulSoup(result.text, 'html.parser') - list_default = soup.find("div", {"class":"list-default"}) - jobs_page = list_default.find_all("div", {"class":"post"}) - - for job in jobs_page: - #job = extract_job(jobs_page) - companys_a = job.find("div", {"class":"post-list-corp"}).find("a") - companys = companys_a.string - if companys is not None: - companys = companys - else : - companys = companys_a['title'] - positions = job.find("div", {"class":"post-list-info"}).find("a")["title"] - locations = job.find("div", {"class":"post-list-info"}).find("p").find("span", {"class":"loc short"}).string - # ##질문!!! 여기서 구, 동을 가져오고 싶다. - # # job_type = job.find("div", {"class":"job_condition"}).find_all("span").string - links = job.find("div", {"class":"post-list-info"}).find("a")["href"] - links = f'http://www.jobkorea.co.kr{links}' - - - # jobs_kind = {'company':companys, 'positions':positions, 'locations':locations, 'links':links, 'job_type':job_type} - jobs_kind = {'companys':companys, 'positions':positions, 'locations':locations, 'links':links } - - # print(jobs_kind) - jk_jobs.append(jobs_kind) - - return jk_jobs - -def jk_get_jobs(input_keyword_recieve, input_location_recieve, input_jobtype_recieve): - - - if input_jobtype_recieve == '전체(근무 형태)': - input_jobtype = '' - elif input_jobtype_recieve == '정규직': - input_jobtype = 1 - elif input_jobtype_recieve == '계약직': - input_jobtype = 2 - elif input_jobtype_recieve == '인턴': - input_jobtype = 3 - elif input_jobtype_recieve == '아르바이트': - input_jobtype = 7 - elif input_jobtype_recieve == '병역특례': - input_jobtype = 9 - - - if input_location_recieve == '전체(희망 지역)': - input_location = '' - elif input_location_recieve == '서울': - input_location = 'I000' - elif input_location_recieve == '경기': - input_location = 'B000' - elif input_location_recieve == '인천': - input_location = 'K000' - elif input_location_recieve == '부산': - input_location = 'H000' - elif input_location_recieve == '대구': - input_location = 'F000' - elif input_location_recieve == '광주': - input_location = 'E000' - elif input_location_recieve == '대전': - input_location = 'G000' - elif input_location_recieve == '울산': - input_location = 'J000' - elif input_location_recieve == '세종': - input_location = '1000' - elif input_location_recieve == '강원': - input_location = 'A000' - elif input_location_recieve == '경남': - input_location = 'C000' - elif input_location_recieve == '경북': - input_location = 'D000' - elif input_location_recieve == '전남': - input_location = 'L000' - elif input_location_recieve == '전북': - input_location = 'M000' - elif input_location_recieve == '충남': - input_location = 'O000' - elif input_location_recieve == '충북': - input_location = 'P000' - elif input_location_recieve == '제주': - input_location = 'N000' - - - print("검색어는", input_keyword_recieve) - print("근무형태 입력은", input_jobtype) - print("위치 입력은", input_location) - - global URL - global job_type_box - - URL = f'http://www.jobkorea.co.kr/Search/?stext={input_keyword_recieve}&local={input_location}&jobtype={input_jobtype}&tabType=recruit' - - print(URL) - last_page = get_last_page() # 최대 페이지를 정의하는 함수를 변수에 넣는다. - jk_jobs = extract_jobs(last_page) #최대 페이지를 정의하는 함수를 넣은 변수를 인자로 넣고 함수를 실행한다. - - return jk_jobs - # return jsonify ({'result':'success','jk_jobs':jk_jobs}) \ No newline at end of file diff --git a/Jobs_Collections/news.py b/Jobs_Collections/news.py deleted file mode 100644 index e55edbc..0000000 --- a/Jobs_Collections/news.py +++ /dev/null @@ -1,60 +0,0 @@ - -from bs4 import BeautifulSoup -import requests -import json -from flask import Flask, render_template, jsonify, request - - -def news_card(): - news_result = requests.get( - 'https://search.naver.com/search.naver?where=news&sm=tab_jum&query=%EC%B7%A8%EC%97%85') - # 뷰티풀숩을 사용해 Html을 전체 가져온다. - news_soup = BeautifulSoup(news_result.text, 'html.parser') - # page 수를 찾기 위해 해당 div를 가져와서 확인한다. - news_result = requests.get( - 'https://search.naver.com/search.naver?where=news&sm=tab_jum&query=%EC%B7%A8%EC%97%85') - # 뷰티풀숩을 사용해 Html을 전체 가져온다. - news_soup = BeautifulSoup(news_result.text, 'html.parser') - news_div = news_soup.find("div", {"class": "news mynews section _prs_nws"}) - news_ul = news_div.find("ul", {"class": "type01"}) - news_li = news_ul.find_all("div", {"class": "thumb"}) - news_dl = news_ul.find_all("dl") - - news_link = [] - news_img = [] - news_title = [] - news_content = [] - - news_card = [] - - for news_links in news_li: - news_links = news_links.find("a")["href"] - # print(news_links) - news_link.append(news_links) - - for news_imgs in news_li: - news_imgs = news_imgs.find("img")["src"] - news_imgs = news_imgs.strip("&type=ofullfill80_80_q75_re2%27,") - # print(news_imgs) - news_img.append(news_imgs) - - for news_titles in news_dl: - news_titles = news_titles.find("dt").find("a")["title"] - news_title.append(news_titles) - - for news_contents in news_dl: - total_news_contents = news_contents.find_all( - "dd")[1].get_text(strip=True) - news_content.append(total_news_contents) - - # print(dd_content) - # sub_news_contents = news_contents.find_all("dd", {"class":"text_inline"}) - #news_contents = total_news_contents.replace(sub_news_contents,'') - # print(total_news_contents) - - for n in range(8): - news_cards = {"news_img": news_img[n], "news_title": news_title[n], - "news_link": news_link[n], "news_content": news_content[n]} - #news_card ={"news_img":news_img, "news_title":news_title, "news_link":news_link} - news_card.append(news_cards) - return jsonify ({'result':'success','news_card':news_card}) \ No newline at end of file diff --git a/Jobs_Collections/saramin.py b/Jobs_Collections/saramin.py deleted file mode 100644 index 6699941..0000000 --- a/Jobs_Collections/saramin.py +++ /dev/null @@ -1,126 +0,0 @@ - -from bs4 import BeautifulSoup -import requests -import json -from flask import Flask, render_template, jsonify, request - -global URL -global URL_op - - -def get_last_page(): - result = requests.get(URL) - - # 뷰티풀숩을 사용해 Html을 전체 가져온다. - soup = BeautifulSoup(result.text, 'html.parser') - pagination = soup.find("div", {"class":"pagination"}).find_all("span") - - if pagination is not None: - last_page = pagination[-1].get_text() - return int(last_page) - else : - return 0 - -def extract_jobs(last_page): - sa_jobs = [] - # for page in range(last_page): - for page in range(1): - #for page in range(1): - print(f"Saramin page : {page+1}") - result = requests.get(URL+f'&recruitPage={page+1}'+URL_op) - print(URL+f'&recruitPage={page+1}'+URL_op) - soup = BeautifulSoup(result.text, 'html.parser') - jobs_page = soup.find_all("div", {"class":"item_recruit"}) - - - for job in jobs_page: - #job = extract_job(jobs_page) - companys = job.find("strong", {"class":"corp_name"}).find("a")["title"] - positions = job.find("h2", {"class":"job_tit"}).find("a")["title"] - locations = job.find("div", {"class":"job_condition"}).find("a").string - ##질문!!! 여기서 구, 동을 가져오고 싶다. - #job_type = job.find("div", {"class":"job_condition"}).find_all("span")[3].string - links = job.find("h2", {"class":"job_tit"}).find("a")["href"] - links = f'http://www.saramin.co.kr{links}' - jobs_kind = {'companys':companys, 'positions':positions, 'locations':locations, 'links':links } - - - #print(jobs_kind) - sa_jobs.append(jobs_kind) - - # print(sa_jobs) - return sa_jobs - -def sa_get_jobs(input_keyword_recieve, input_location_recieve, input_jobtype_recieve): - - - - if input_jobtype_recieve == '전체(근무 형태)': - input_jobtype = '' - elif input_jobtype_recieve == '정규직': - input_jobtype = 1 - elif input_jobtype_recieve == '계약직': - input_jobtype = 2 - elif input_jobtype_recieve == '인턴': - input_jobtype = 4 - elif input_jobtype_recieve == '아르바이트': - input_jobtype = 5 - elif input_jobtype_recieve == '병역특례': - input_jobtype = 3 - - - if input_location_recieve == '전체(희망 지역)': - input_location = '' - elif input_location_recieve == '서울': - input_location = 101000 - elif input_location_recieve == '경기': - input_location = 102000 - elif input_location_recieve == '인천': - input_location = 108000 - elif input_location_recieve == '부산': - input_location = 106000 - elif input_location_recieve == '대구': - input_location = 104000 - elif input_location_recieve == '광주': - input_location = 103000 - elif input_location_recieve == '대전': - input_location = 105000 - elif input_location_recieve == '울산': - input_location = 107000 - elif input_location_recieve == '세종': - input_location = 118000 - elif input_location_recieve == '강원': - input_location = 109000 - elif input_location_recieve == '경남': - input_location = 110000 - elif input_location_recieve == '경북': - input_location = 111000 - elif input_location_recieve == '전남': - input_location = 112000 - elif input_location_recieve == '전북': - input_location = 113000 - elif input_location_recieve == '충남': - input_location = 115000 - elif input_location_recieve == '충북': - input_location = 114000 - elif input_location_recieve == '제주': - input_location = 116000 - - print("검색어는", input_keyword_recieve) - print("근무형태 입력은", input_jobtype) - print("위치 입력은", input_location) - - global URL - global URL_op - - URL_op = f'&recruitSort=relation&recruitPageCount=40&inner_com_type=&quick_apply=' - URL = f'http://www.saramin.co.kr/zf_user/search/recruit?searchType=search&searchword={input_keyword_recieve}&company_cd=0,1,2,3,4,5,6,7,9&loc_mcd={input_location}&job_type={input_jobtype}&panel_type=&search_optional_item=y&search_done=y&panel_count=y' - - - last_page = get_last_page() # 최대 페이지를 정의하는 함수를 변수에 넣는다. - sa_jobs = extract_jobs(last_page) #최대 페이지를 정의하는 함수를 넣은 변수를 인자로 넣고 함수를 실행한다. - # print(sa_jobs) - # return sa_jobs - - return sa_jobs - # return jsonify ({'result':'success','sa_jobs':sa_jobs}) \ No newline at end of file diff --git a/Jobs_Collections/static/.DS_Store b/Jobs_Collections/static/.DS_Store deleted file mode 100644 index ebff0d3..0000000 Binary files a/Jobs_Collections/static/.DS_Store and /dev/null differ diff --git a/Jobs_Collections/static/favicon.png b/Jobs_Collections/static/favicon.png deleted file mode 100644 index 9685a41..0000000 Binary files a/Jobs_Collections/static/favicon.png and /dev/null differ diff --git a/Jobs_Collections/static/header.css b/Jobs_Collections/static/header.css deleted file mode 100644 index 3cc77e2..0000000 --- a/Jobs_Collections/static/header.css +++ /dev/null @@ -1,198 +0,0 @@ -*{ - box-sizing: border-box; -} - -#header_bar{ - margin: 0 auto; - height: 100px; - background-color: black; -} - -#main_bar{ - width: 100%; - height: 250px; -} - -.window_reload_js{ - display: inline-block; - margin: 18px 0px 0px 20px; - font-size: 48px; - color: white; - font-family: 'MuseoModerno', cursive; -} - -.Indeed_show{ - display: inline-block; - margin: 25px 60px 0px 60px; - float: right; - color: white; -} - -.Saramin_show{ - display: inline-block; - margin: 18px 60px 0px 60px; - float: right; - color: white; -} - -.JobKorea_show{ - display: inline-block; - margin: 18px 60px 0px 60px; - float: right; - color: white; -} - -.Total_show{ - display: inline-block; - margin: 18px 60px 0px 60px; - float: right; - color: white; -} - -.Like_show{ - display: inline-block; - margin: 18px 60px 0px 60px; - float: right; - color: #f8585b; - text-align: center; -} - -/* header{ - margin: 0 auto; - width: 1080px; - height: 350px; -} */ - -#header_logo{ - width: 100%; - height: 250px; - background-image: url("8.jpg"); -} - -#header_input{ - margin: 0 auto; - width: 1019px; - height: 70px; -} - -#main_logo{ - width: 20%; - height: 250px; - display: inline-block; - float: left; -} - -#main_img{ - width: 80%; - height: 250px; - display: inline-block; -} - -#input_div{ - width: 880px; - margin: 50px 85px 50px 85px; - display: inline-block; - -} - -.input_company{ - width: 320px; - height: 40px; - margin-right: 15px; - float: left; -} - -.input_location{ - width: 140px; - height: 40px; - border: 2px 0px 2px 0px; - padding: 1px 0px 10x 0px; - margin-right: 15px; - float: left; -} - -.input_jobtype{ - width: 140px; - height: 40px; - border: 2px 0px 2px 0px; - padding: 1px 0px 10x 0px; - margin-right: 15px; - float: left; -} - -.input_potal{ - width: 140px; - height: 40px; - border: 2px 0px 2px 0px; - padding: 1px 0px 10x 0px; - margin-right: 15px; - float: left; -} - -.search_btn{ - width: 50px; - height: 40px; - vertical-align: middle; - /* margin-left: 10px; */ - vertical-align: auto; - border-radius: 10%; -} - - -.showing_class { - display: block; -} - -.hiding_class { - display: none; -} - -#fixedbtn { - position: fixed; - right: 10px; - bottom: 0px; - z-index: 1000 -} - -#tooltip_company{ - font-family: 'Malgun Gothic'; -} - -#tooltip_main{ - height: 40px; - margin-top: 10px; - text-align: center; - font-size: 20px; -} - -.like_list_span{ - width: 150px; - height: 21px; - line-height: 21px; - /* overflow: hidden; */ - /* white-space: normal; */ - margin: 3px; - -} - -.sub_like_list_span{ - overflow: hidden; - width: 122px; - text-overflow: ellipsis; - height: 21px; - line-height: 28px; - /* display: inline-block; */ - display: inline-block; - overflow:hidden; - white-space:nowrap; - float: left; -} - - - -.like_del_btn{ - float: right; - height: 24px; - font-size: 1px; - border-radius: 10%; -} \ No newline at end of file diff --git a/Jobs_Collections/static/heart.png b/Jobs_Collections/static/heart.png deleted file mode 100644 index 0b910e5..0000000 Binary files a/Jobs_Collections/static/heart.png and /dev/null differ diff --git a/Jobs_Collections/static/loadingbar.css b/Jobs_Collections/static/loadingbar.css deleted file mode 100644 index 7973618..0000000 --- a/Jobs_Collections/static/loadingbar.css +++ /dev/null @@ -1,126 +0,0 @@ - -#loadingbar_center { - width: 880px; - height: 250px; - text-align: center; - margin-top: 300px; -} - - -#loading_news { - width: 880px; - height: 250px; - text-align: center; - margin-top: 250px; -} - -.hiding_class{ - display: none; -} - - -/* 로딩바 */ - - - - -@keyframes ldio-dmlkq2kuyw { -0% { - opacity: 1; - backface-visibility: hidden; - transform: translateZ(0) scale(1.5,1.5); -} 100% { - opacity: 0; - backface-visibility: hidden; - transform: translateZ(0) scale(1,1); -} -} -.ldio-dmlkq2kuyw div > div { -position: absolute; -width: 13.32px; -height: 13.32px; -border-radius: 50%; -background: #ff727d; -animation: ldio-dmlkq2kuyw 2.564102564102564s linear infinite; -}.ldio-dmlkq2kuyw div:nth-child(1) > div { -left: 82.5px; -top: 48.50000000000001px; -animation-delay: -2.2435897435897436s; -} -.ldio-dmlkq2kuyw > div:nth-child(1) { -transform: rotate(0deg); -transform-origin: 89.16px 55.160000000000004px; -}.ldio-dmlkq2kuyw div:nth-child(2) > div { -left: 72.5px; -top: 72.5px; -animation-delay: -1.923076923076923s; -} -.ldio-dmlkq2kuyw > div:nth-child(2) { -transform: rotate(45deg); -transform-origin: 79.16px 79.16px; -}.ldio-dmlkq2kuyw div:nth-child(3) > div { -left: 48.50000000000001px; -top: 82.5px; -animation-delay: -1.6025641025641024s; -} -.ldio-dmlkq2kuyw > div:nth-child(3) { -transform: rotate(90deg); -transform-origin: 55.160000000000004px 89.16px; -}.ldio-dmlkq2kuyw div:nth-child(4) > div { -left: 25.500000000000007px; -top: 72.5px; -animation-delay: -1.282051282051282s; -} -.ldio-dmlkq2kuyw > div:nth-child(4) { -transform: rotate(135deg); -transform-origin: 32.160000000000004px 79.16px; -}.ldio-dmlkq2kuyw div:nth-child(5) > div { -left: 15.500000000000007px; -top: 48.50000000000001px; -animation-delay: -0.9615384615384615s; -} -.ldio-dmlkq2kuyw > div:nth-child(5) { -transform: rotate(180deg); -transform-origin: 22.160000000000004px 55.160000000000004px; -}.ldio-dmlkq2kuyw div:nth-child(6) > div { -left: 25.500000000000007px; -top: 25.500000000000007px; -animation-delay: -0.641025641025641s; -} -.ldio-dmlkq2kuyw > div:nth-child(6) { -transform: rotate(225deg); -transform-origin: 32.160000000000004px 32.160000000000004px; -}.ldio-dmlkq2kuyw div:nth-child(7) > div { -left: 48.50000000000001px; -top: 15.500000000000007px; -animation-delay: -0.3205128205128205s; -} -.ldio-dmlkq2kuyw > div:nth-child(7) { -transform: rotate(270deg); -transform-origin: 55.160000000000004px 22.160000000000004px; -}.ldio-dmlkq2kuyw div:nth-child(8) > div { -left: 72.5px; -top: 25.500000000000007px; -animation-delay: 0s; -} -.ldio-dmlkq2kuyw > div:nth-child(8) { -transform: rotate(315deg); -transform-origin: 79.16px 32.160000000000004px; -} -.loadingio-spinner-spin-87fuqmn8sh4 { -width: 111px; -height: 111px; -display: inline-block; -overflow: hidden; -background: #ffffff; -} -.ldio-dmlkq2kuyw { -width: 100%; -height: 100%; -position: relative; -transform: translateZ(0) scale(1); -backface-visibility: hidden; -transform-origin: 0 0; /* see note above */ -} -.ldio-dmlkq2kuyw div { box-sizing: content-box; } -/* generated by https://loading.io/ */ \ No newline at end of file diff --git a/Jobs_Collections/static/news.js b/Jobs_Collections/static/news.js deleted file mode 100644 index 706010e..0000000 --- a/Jobs_Collections/static/news.js +++ /dev/null @@ -1,46 +0,0 @@ - -$(document).ready(function () { - news_readey(); - console.log('준비완료'); -}); - -// const loadingbar_news = document.querySelector("#loading_news") 질문 1번 - -function news_readey() { - $('#recruit_news').empty() - $.ajax({ - type: "GET", - url: "/api/news", - data: {}, - success: function (response) { - $(loading_news).addClass("hiding_class"); - // loadingbar_news.classList.add('hiding_class') 질문 1번 - let news_card = response['news_card']; - for (let i = 0; i < news_card.length; i++) { - let r_news_card = news_card[i] - - let news_content = r_news_card['news_content'] - let news_link = r_news_card['news_link'] - let news_img = r_news_card['news_img'] - let news_title = r_news_card['news_title'] - - let temp_html = ``; - $('#recruit_news').append(temp_html); - - } - } - }) -} \ No newline at end of file diff --git a/Jobs_Collections/static/pocket.js b/Jobs_Collections/static/pocket.js deleted file mode 100644 index d55fae9..0000000 --- a/Jobs_Collections/static/pocket.js +++ /dev/null @@ -1,24 +0,0 @@ -const pocket_bar_1 = document.querySelector("#fixedbtn") -const tooltip = document.querySelector(".balloon") - -const balloon = "balloon hiding_class" - - - -function handleClick_tooltip() { - const current_class = tooltip; - - if(current_class.className == balloon){ - tooltip.classList.remove('hiding_class'); - } - else{ - tooltip.classList.add('hiding_class'); - } - -} - - -function init() { - pocket_bar_1.addEventListener("click", handleClick_tooltip); -} -init() \ No newline at end of file diff --git a/Jobs_Collections/static/pocket.png b/Jobs_Collections/static/pocket.png deleted file mode 100644 index 6a3c998..0000000 Binary files a/Jobs_Collections/static/pocket.png and /dev/null differ diff --git a/Jobs_Collections/static/reload.js b/Jobs_Collections/static/reload.js deleted file mode 100644 index 0925a3d..0000000 --- a/Jobs_Collections/static/reload.js +++ /dev/null @@ -1,14 +0,0 @@ - -const main_name = document.querySelector(".window_reload_js"); -const click_hiding_logo = document.querySelector("#section_center"); - -function handleClick_logo(){ - window.location.reload(); - - -} - -function init(){ - main_name.addEventListener("click", handleClick_logo); -} -init(); \ No newline at end of file diff --git a/Jobs_Collections/static/search.js b/Jobs_Collections/static/search.js deleted file mode 100644 index 0b167fa..0000000 --- a/Jobs_Collections/static/search.js +++ /dev/null @@ -1,674 +0,0 @@ - -const header_input = document.querySelector("#header_input"); -const input_div = header_input.querySelector("#input_div"); -const search_btn = input_div.querySelector(".search_btn"); - -const Total_logo = document.querySelector(".Total_show") -const Job_Koera_logo = document.querySelector(".JobKorea_show") -const Saramin_logo = document.querySelector(".Saramin_show") -const Indeed_logo = document.querySelector(".Indeed_show") - -const Total_class = document.querySelector("#section_total") -const Job_Koera_class = document.querySelector("#section_Job_Korea") -const Saramin_class = document.querySelector("#section_Saramin") -const Indeed_class = document.querySelector("#section_Indeed") - - -const section_recruit_info = document.querySelector("#section_total"); -const section_news_info = document.querySelector("#hot_jobs"); - -const jobs_num_box = document.querySelector("#recruit_info_number") -const jobs_num = jobs_num_box.querySelector("h4") - -const jobs_potal_div = document.querySelector("#recruit_info_box") -const jobs_potal_h = jobs_potal_div.querySelector("h2") -const jobs_potal = jobs_potal_h.querySelector("strong") - - -const input_keyword_box = document.querySelector(".input_company") -const input_potal_box = document.querySelector(".input_potal") -const input_location_box = document.querySelector(".input_location") -const input_jobtype_box = document.querySelector(".input_jobtype") - -const pocket_bar = document.querySelector("#fixedbtn") - -const like_list = document.querySelector("#like_list") - -const like_list_LS = 'like_company'; - - -const loadingbar = document.querySelector("#loadingbar_center") -const None_info = document.querySelector("#None_info") -const recruit_info = document.querySelector("#recruit_info") - -let like_list_ar = [] - - - -function like_del(del_company, del_link) { - const del_btn = event.target; - const li = del_btn.parentNode.parentNode; - like_list.removeChild(li); - - localStorage.removeItem('test'); - // console.log(localStorage.getItem(like_list_LS)) - // console.log(like_list_ar.length) - - for (let i = 0; i < like_list_ar.length; i++) { - if (like_list_ar[i]['like_company'] === del_company) { - like_list_ar.splice(i, 1) - console.log("remove", like_list_ar[i]) - } - } - save_like_list(); - - - // const loaded_like = localStorage.getItem(like_list_LS); - - // console.log(loaded_like) - - // if (loaded_like !== null) { - // const parsed_like = JSON.parse(loaded_like); - // parsed_like.forEach(function (like) { - // if (like['like_company']===del_company){ - // console.log(like) - // console.log("삭제함수", del_company) - // localStorage.removeItem(like); - // }}) - // } - - - // const like_del_LS = like_list_ar.filter(function(like_list_ar){ - // return - // }) - -} - -const pocket_ar = [] - -function handleClick_like(like_company, like_link) { - console.log(typeof (like_company)) - console.log(like_list_ar) - var LS_like_index = like_list_ar.findIndex(i => i.like_company === like_company) - if (LS_like_index !== -1) { - alert("관심기업에 이미 등록되어있습니다.") - } - else { - - if (like_list_ar.length < 18) { - let like_html = ``; - // like_list.append(like_html); - $('#like_list').append(like_html); - - const like_list_Obj = { - 'like_company': like_company, - 'like_link': like_link - - }; - like_list_ar.push(like_list_Obj) - save_like_list(); - } - else { - alert("관심기업은 최대 18개까지만 등록 가능합니다.") - - } - } -} - - - - - -function handleClick_search() { - - let input_keyword = input_keyword_box.value - let input_potal = input_potal_box.value - let input_location = input_location_box.value - let input_jobtype = input_jobtype_box.value - - console.log(`검색어 : ${input_keyword}, 포탈 : ${input_potal}, 위치 : ${input_location}, 고용 형태 : ${input_jobtype}`) - - if (input_keyword == '') { - alert("검색어를 입력하세요.") - return 0 - } - - - if (input_location == '전체 (희망 지역)') { - input_location = '' - } - - if (input_jobtype == '전체 (근무 형태)') { - input_jobtype = '' - } - - // console.log(`${input_keyword}를 검색합니다.`) - - if (input_potal == '전체 (포탈 선택)') { - job_total_give(input_keyword, input_location, input_jobtype) - } - - else if (input_potal == 'Job-korea') { - job_korea_jobs_give(input_keyword, input_location, input_jobtype) - } - - else if (input_potal == 'Saram-in') { - saramin_jobs_give(input_keyword, input_location, input_jobtype) - } - - else if (input_potal == 'Indeed') { - indeed_jobs_give(input_keyword, input_location, input_jobtype) - } - - section_recruit_info.classList.remove('hiding_class'); - section_news_info.classList.add('hiding_class'); - - - -} - - -function indeed_jobs_give(input_keyword, input_location, input_jobtype) { - None_info.classList.add('hiding_class'); - loadingbar.classList.remove('hiding_class'); - pocket_bar.classList.add('hiding_class'); - $(recruit_info).addClass("hiding_class"); - $('.balloon').addClass("hiding_class"); - $('#total_recruit_info').empty() - $.ajax({ - type: "GET", - url: `/api/indeed?input_keyword_give=` + input_keyword + `&input_location_give=` + input_location + `&input_jobtype_give=` + input_jobtype, - data: {}, - error: function () { - alert('일치하는 정보가 없습니다.'); - None_info.classList.remove('hiding_class') - loadingbar.classList.add('hiding_class') - $(recruit_info).addClass("hiding_class"); - pocket_bar.classList.remove('hiding_class'); - }, - success: function (response) { - $(recruit_info).removeClass("hiding_class"); - let id_jobs = response['id_jobs']; - // console.log(id_jobs.length) - if (id_jobs.length === 0) { - alert('일치하는 정보가 없습니다.'); - None_info.classList.remove('hiding_class') - loadingbar.classList.add('hiding_class') - $(recruit_info).addClass("hiding_class"); - pocket_bar.classList.remove('hiding_class'); - } - - - - for (let i = 0; i < id_jobs.length; i++) { - let r_id_jobs = id_jobs[i] - let company = r_id_jobs['companys'] - let position = r_id_jobs['positions'] - let location = r_id_jobs['locations'] - let link = r_id_jobs['links'] - - let temp_html = `
-
- -
-
- - ${position} - -
-
-
- 위치 : ${location} -
-
- -
-
-
-
- - -
-
-
`; - $('#total_recruit_info').append(temp_html); - jobs_num.innerText = `총 ${id_jobs.length}개의 채용정보`; - jobs_potal.innerText = 'Indeed의 채용정보'; - loadingbar.classList.add('hiding_class'); - pocket_bar.classList.remove('hiding_class'); - - - } - } - }) - -} - - -function saramin_jobs_give(input_keyword, input_location, input_jobtype) { - None_info.classList.add('hiding_class'); - loadingbar.classList.remove('hiding_class'); - $(recruit_info).addClass("hiding_class"); - pocket_bar.classList.add('hiding_class'); - $('.balloon').addClass("hiding_class"); - $('#total_recruit_info').empty() - $.ajax({ - type: "GET", - url: `/api/saramin?input_keyword_give=` + input_keyword + `&input_location_give=` + input_location + `&input_jobtype_give=` + input_jobtype, - data: {}, - error: function () { - alert('일치하는 정보가 없습니다.'); - None_info.classList.remove('hiding_class') - loadingbar.classList.add('hiding_class') - $(recruit_info).addClass("hiding_class"); - pocket_bar.classList.remove('hiding_class'); - }, - success: function (response) { - $(recruit_info).removeClass("hiding_class"); - let sa_jobs = response['sa_jobs']; - for (let i = 0; i < sa_jobs.length; i++) { - let r_sa_jobs = sa_jobs[i] - - let company = r_sa_jobs['companys'] - let position = r_sa_jobs['positions'] - let location = r_sa_jobs['locations'] - let link = r_sa_jobs['links'] - - let temp_html = `
-
- -
-
- - ${position} - -
-
-
- 위치 : ${location} -
-
- -
-
-
-
- - -
-
-
`; - $('#total_recruit_info').append(temp_html); - jobs_num.innerText = `총 ${sa_jobs.length}개의 채용정보`; - jobs_potal.innerText = 'Saram-in의 채용정보'; - loadingbar.classList.add('hiding_class'); - pocket_bar.classList.remove('hiding_class'); - - } - } - }) -} - - -function job_korea_jobs_give(input_keyword, input_location, input_jobtype) { - None_info.classList.add('hiding_class'); - loadingbar.classList.remove('hiding_class'); - $(recruit_info).addClass("hiding_class"); - pocket_bar.classList.add('hiding_class'); - $('.balloon').addClass("hiding_class"); - $('#total_recruit_info').empty() - $.ajax({ - type: "GET", - url: `/api/job_korea?input_keyword_give=` + input_keyword + `&input_location_give=` + input_location + `&input_jobtype_give=` + input_jobtype, - data: {}, - error: function () { - alert('일치하는 정보가 없습니다.'); - None_info.classList.remove('hiding_class') - loadingbar.classList.add('hiding_class') - $(recruit_info).addClass("hiding_class"); - pocket_bar.classList.remove('hiding_class'); - }, - success: function (response) { - $(recruit_info).removeClass("hiding_class"); - let jk_jobs = response['jk_jobs']; - for (let i = 0; i < jk_jobs.length; i++) { - let r_jk_jobs = jk_jobs[i] - - let company = r_jk_jobs['companys'] - let position = r_jk_jobs['positions'] - let location = r_jk_jobs['locations'] - let link = r_jk_jobs['links'] - - let temp_html = `
-
- -
-
- - ${position} - -
-
-
- 위치 : ${location} -
-
- -
-
-
-
- - -
-
-
`; - $('#total_recruit_info').append(temp_html); - jobs_num.innerText = `총 ${jk_jobs.length}개의 채용정보`; - jobs_potal.innerText = 'Job-korea의 채용정보'; - loadingbar.classList.add('hiding_class'); - pocket_bar.classList.remove('hiding_class'); - - } - } - }) -} - - -function job_total_give(input_keyword, input_location, input_jobtype) { - None_info.classList.add('hiding_class'); - loadingbar.classList.remove('hiding_class'); - $(recruit_info).addClass("hiding_class"); - pocket_bar.classList.add('hiding_class'); - $('.balloon').addClass("hiding_class"); - $('#total_recruit_info').empty() - $.ajax({ - type: "GET", - url: `/api/total?input_keyword_give=` + input_keyword + `&input_location_give=` + input_location + `&input_jobtype_give=` + input_jobtype, - data: {}, - error: function () { - alert('일치하는 정보가 없습니다.'); - None_info.classList.remove('hiding_class') - loadingbar.classList.add('hiding_class') - $(recruit_info).addClass("hiding_class"); - pocket_bar.classList.remove('hiding_class'); - }, - success: function (response) { - $(recruit_info).removeClass("hiding_class"); - let jk_jobs = response['jk_jobs']; - let id_jobs = response['id_jobs']; - let sa_jobs = response['sa_jobs']; - // console.log(jk_jobs) - for (let i = 0; i < jk_jobs.length; i++) { - let r_jk_jobs = jk_jobs[i] - - let company = r_jk_jobs['companys'] - let position = r_jk_jobs['positions'] - let location = r_jk_jobs['locations'] - let link = r_jk_jobs['links'] - - let temp_html = `
-
- -
-
- - ${position} - -
-
-
- 위치 : ${location} -
-
- -
-
-
-
- - -
-
-
`; - $('#total_recruit_info').append(temp_html); - jobs_num.innerText = `총 ${jk_jobs.length + id_jobs.length + sa_jobs.length}개의 채용정보`; - jobs_potal.innerText = '전체포탈의 채용정보'; - loadingbar.classList.add('hiding_class'); - pocket_bar.classList.remove('hiding_class'); - - } - - for (let i = 0; i < sa_jobs.length; i++) { - let r_sa_jobs = sa_jobs[i] - - let company = r_sa_jobs['companys'] - let position = r_sa_jobs['positions'] - let location = r_sa_jobs['locations'] - let link = r_sa_jobs['links'] - - let temp_html = `
-
- -
-
- - ${position} - -
-
-
- 위치 : ${location} -
-
- -
-
-
-
- - -
-
-
`; - $('#total_recruit_info').append(temp_html); - } - - for (let i = 0; i < id_jobs.length; i++) { - let r_id_jobs = id_jobs[i] - - let company = r_id_jobs['companys'] - let position = r_id_jobs['positions'] - let location = r_id_jobs['locations'] - let link = r_id_jobs['links'] - - let temp_html = `
-
- -
-
- - ${position} - -
-
-
- 위치 : ${location} -
-
- -
-
-
-
- - -
-
-
`; - $('#total_recruit_info').append(temp_html); - } - } - }) -} - -function print_like(like) { - let like_company_LS = like['like_company'] - let like_link_LS = like['like_link'] - - let like_html = - ``; - // like_list.append(like_html); - $('#like_list').append(like_html); - - const like_list_Obj = { - 'like_company': like_company_LS, - 'like_link': like_link_LS - // id :newId - }; - like_list_ar.push(like_list_Obj) - save_like_list(); - -} - -function save_like_list() { - localStorage.setItem(like_list_LS, JSON.stringify(like_list_ar)); -} - -function load_like() { - const loaded_like = localStorage.getItem(like_list_LS); - if (loaded_like !== null) { - const parsed_like = JSON.parse(loaded_like); - parsed_like.forEach(function (like) { - // console.log(like) - print_like(like) - }) - } -} - - - - -function init() { - - search_btn.addEventListener("click", handleClick_search); - - - load_like(); - - // Total_logo.addEventListener("click", handleClick_search); - // Job_Koera_logo.addEventListener("click", handleClick_Job_Korea); - // Saramin_logo.addEventListener("click", handleClick_Saramin); - // Indeed_logo.addEventListener("click", handleClick_Indeed); -} -init(); \ No newline at end of file diff --git a/Jobs_Collections/static/section_page1.css b/Jobs_Collections/static/section_page1.css deleted file mode 100644 index 68667c5..0000000 --- a/Jobs_Collections/static/section_page1.css +++ /dev/null @@ -1,54 +0,0 @@ -*{ - box-sizing: border-box; -} - -.todays_news{ - font-family: 'Jua', sans-serif; -} - -#hot_jobs{ - width: 880px; - height: 850px; /*섹션의 전체 높이를 임의로 지정해놓음.*/ - margin: 50px 100px 0px 100px; - background-color: white; -} - -#news_box{ - width: 180px; - height: 300px; - margin: 50px 20px 0px 20px; - display: inline-block; - float: left; - border: 1px solid #dae1e6; -} - -#news_img{ - width: 180px; - height: 120px; -} - -#news_title{ - width: 160px; - height: 60px; - margin: 10px 10px 10px 10px; - font-weight: bold; - font-size: 14px; - overflow: hidden; - /* white-space: normal; */ - text-overflow: ellipsis; -} - -#news_content{ - width: 160px; - height: 80px; - margin: 0px 10px 10px 10px; - font-size: 11px; - overflow: hidden; - /* white-space: normal; */ - text-overflow: ellipsis; -} - -.news_class{ -text-decoration: none; -color: black; -} \ No newline at end of file diff --git a/Jobs_Collections/static/section_page2.css b/Jobs_Collections/static/section_page2.css deleted file mode 100644 index 6b407d2..0000000 --- a/Jobs_Collections/static/section_page2.css +++ /dev/null @@ -1,157 +0,0 @@ -*{ - box-sizing: border-box; - -} -section{ - margin: 0 auto; - width: 1080px; - /* background-color: #e5e6eb; */ - font-family: 'Malgun Gothic'; -} - -#section_total{ - width: 880px; - /*섹션의 전체 높이를 임의로 지정해놓음.*/ - margin: 50px 100px 0px 100px; - background-color: white; -} - -#section_Job_Korea{ - width: 880px; - /*섹션의 전체 높이를 임의로 지정해놓음.*/ - margin: 50px 100px 0px 100px; - background-color: white; -} - -#section_Saramin{ - width: 880px; - /*섹션의 전체 높이를 임의로 지정해놓음.*/ - margin: 50px 100px 0px 100px; - background-color: white; -} - -#section_Indeed{ - width: 880px; - /*섹션의 전체 높이를 임의로 지정해놓음.*/ - margin: 50px 100px 0px 100px; - background-color: white; -} - - - -#recruit_info{ - height: 100px; - margin-bottom: 40px; -} - -#recruit_info_box{ - height: 70px; - display: inline-block; -} -#recruit_info_box >h2{ - margin: 20px 0px 0px 20px; - vertical-align: middle; -} - -#recruit_info_number{ - height: 30px; - -} - -#recruit_info_number >h4{ - margin: 0px 0px 0px 20px; -} - -#recruit_post{ - width: 880px; - height: 90px; - border: 1px solid #dae1e6; - -} - -/* #recruit_post_info{ - width: 50%; - height: 120px; - margin: 25px 40px 25px 100px; - float: left; -} */ - -#recruit_post_link{ - width: 98px; - height: 90px; - - border-left: 0.1px solid #dae1e6; - display: inline-block; - text-align: center; -} - -#support_btn{ - height: 25px; - margin: 15px 0px 10px; - border: none; -} - -.pink_btn{ - color:#fff; - background-color: #f8585b; - border: none; - height: 25px; -} - - -#like_btn{ - height: 25px; - margin: 15px 0px 10px; -} - -#company_name{ - width: 180px; - height: 20px; - display: inline-block; - float: left; - - text-align: center; - margin: 35px 0px 35px 20px; -} -.a_companys_name{ - text-decoration: none; - color: black; -} - -#position_name{ - width: 460px; - height: 25px; - display: inline-block; - float: left; - margin: 10px 60px 10px 60px; - -} - -#other_name{ - width: 460px; - height: 25px; - display: inline-block; - float: left; - margin: 10px 60px 10px 60px; -} - -#location_name{ - display: inline-block; - float: left; - font-size: 11px; - width: 300px; -} - -#income_name{ - display: inline-block; - float: left; - margin-left: 20px; - font-size: 13px; - width: 90px; -} - -#None_info{ - text-align: center; - height: 300px; - margin-top: 330px; -} \ No newline at end of file diff --git a/Jobs_Collections/templates/Jobs_collection.html b/Jobs_Collections/templates/Jobs_collection.html deleted file mode 100644 index 3eec5cb..0000000 --- a/Jobs_Collections/templates/Jobs_collection.html +++ /dev/null @@ -1,290 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Jobs Collection - - - - - -
-
-
- 관심있는 기업 목록 -
-
-
    - -
-
-
-
- - -
- -
- -

Collection Jobs

- -
- -
-
- - - - - - - - - - - -
-
-
- - - -
-
- -
-
-

전체 포탈의 채용정보

-
-
-

채용정보 갯수

-
-
- - - -
-
-
-
-
- - - -
-

일치하는 채용 정보가 없습니다.

-
- -
- - - -
-
-
- - - - - -
-
-
-

오늘의 취업 관련 뉴스

-
- -
- -
-
-
- -
- - -
- - - -
- - - -
- -
- - - -
- - - -
- -
- - - - - - - - - - \ No newline at end of file diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/Flask-1.1.2.dist-info/INSTALLER b/Jobs_Collections/venv/Lib/python3.8/site-packages/Flask-1.1.2.dist-info/INSTALLER deleted file mode 100644 index a1b589e..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/Flask-1.1.2.dist-info/INSTALLER +++ /dev/null @@ -1 +0,0 @@ -pip diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/Flask-1.1.2.dist-info/LICENSE.rst b/Jobs_Collections/venv/Lib/python3.8/site-packages/Flask-1.1.2.dist-info/LICENSE.rst deleted file mode 100644 index 9d227a0..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/Flask-1.1.2.dist-info/LICENSE.rst +++ /dev/null @@ -1,28 +0,0 @@ -Copyright 2010 Pallets - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - -1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - -2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - -3. Neither the name of the copyright holder nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A -PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/Flask-1.1.2.dist-info/METADATA b/Jobs_Collections/venv/Lib/python3.8/site-packages/Flask-1.1.2.dist-info/METADATA deleted file mode 100644 index db7fcd1..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/Flask-1.1.2.dist-info/METADATA +++ /dev/null @@ -1,137 +0,0 @@ -Metadata-Version: 2.1 -Name: Flask -Version: 1.1.2 -Summary: A simple framework for building complex web applications. -Home-page: https://palletsprojects.com/p/flask/ -Author: Armin Ronacher -Author-email: armin.ronacher@active-4.com -Maintainer: Pallets -Maintainer-email: contact@palletsprojects.com -License: BSD-3-Clause -Project-URL: Documentation, https://flask.palletsprojects.com/ -Project-URL: Code, https://github.com/pallets/flask -Project-URL: Issue tracker, https://github.com/pallets/flask/issues -Platform: UNKNOWN -Classifier: Development Status :: 5 - Production/Stable -Classifier: Environment :: Web Environment -Classifier: Framework :: Flask -Classifier: Intended Audience :: Developers -Classifier: License :: OSI Approved :: BSD License -Classifier: Operating System :: OS Independent -Classifier: Programming Language :: Python -Classifier: Programming Language :: Python :: 2 -Classifier: Programming Language :: Python :: 2.7 -Classifier: Programming Language :: Python :: 3 -Classifier: Programming Language :: Python :: 3.5 -Classifier: Programming Language :: Python :: 3.6 -Classifier: Programming Language :: Python :: 3.7 -Classifier: Programming Language :: Python :: 3.8 -Classifier: Programming Language :: Python :: Implementation :: CPython -Classifier: Programming Language :: Python :: Implementation :: PyPy -Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content -Classifier: Topic :: Internet :: WWW/HTTP :: WSGI :: Application -Classifier: Topic :: Software Development :: Libraries :: Application Frameworks -Classifier: Topic :: Software Development :: Libraries :: Python Modules -Requires-Python: >=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.* -Requires-Dist: Werkzeug (>=0.15) -Requires-Dist: Jinja2 (>=2.10.1) -Requires-Dist: itsdangerous (>=0.24) -Requires-Dist: click (>=5.1) -Provides-Extra: dev -Requires-Dist: pytest ; extra == 'dev' -Requires-Dist: coverage ; extra == 'dev' -Requires-Dist: tox ; extra == 'dev' -Requires-Dist: sphinx ; extra == 'dev' -Requires-Dist: pallets-sphinx-themes ; extra == 'dev' -Requires-Dist: sphinxcontrib-log-cabinet ; extra == 'dev' -Requires-Dist: sphinx-issues ; extra == 'dev' -Provides-Extra: docs -Requires-Dist: sphinx ; extra == 'docs' -Requires-Dist: pallets-sphinx-themes ; extra == 'docs' -Requires-Dist: sphinxcontrib-log-cabinet ; extra == 'docs' -Requires-Dist: sphinx-issues ; extra == 'docs' -Provides-Extra: dotenv -Requires-Dist: python-dotenv ; extra == 'dotenv' - -Flask -===== - -Flask is a lightweight `WSGI`_ web application framework. It is designed -to make getting started quick and easy, with the ability to scale up to -complex applications. It began as a simple wrapper around `Werkzeug`_ -and `Jinja`_ and has become one of the most popular Python web -application frameworks. - -Flask offers suggestions, but doesn't enforce any dependencies or -project layout. It is up to the developer to choose the tools and -libraries they want to use. There are many extensions provided by the -community that make adding new functionality easy. - - -Installing ----------- - -Install and update using `pip`_: - -.. code-block:: text - - pip install -U Flask - - -A Simple Example ----------------- - -.. code-block:: python - - from flask import Flask - - app = Flask(__name__) - - @app.route("/") - def hello(): - return "Hello, World!" - -.. code-block:: text - - $ env FLASK_APP=hello.py flask run - * Serving Flask app "hello" - * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) - - -Contributing ------------- - -For guidance on setting up a development environment and how to make a -contribution to Flask, see the `contributing guidelines`_. - -.. _contributing guidelines: https://github.com/pallets/flask/blob/master/CONTRIBUTING.rst - - -Donate ------- - -The Pallets organization develops and supports Flask and the libraries -it uses. In order to grow the community of contributors and users, and -allow the maintainers to devote more time to the projects, `please -donate today`_. - -.. _please donate today: https://psfmember.org/civicrm/contribute/transact?reset=1&id=20 - - -Links ------ - -* Website: https://palletsprojects.com/p/flask/ -* Documentation: https://flask.palletsprojects.com/ -* Releases: https://pypi.org/project/Flask/ -* Code: https://github.com/pallets/flask -* Issue tracker: https://github.com/pallets/flask/issues -* Test status: https://dev.azure.com/pallets/flask/_build -* Official chat: https://discord.gg/t6rrQZH - -.. _WSGI: https://wsgi.readthedocs.io -.. _Werkzeug: https://www.palletsprojects.com/p/werkzeug/ -.. _Jinja: https://www.palletsprojects.com/p/jinja/ -.. _pip: https://pip.pypa.io/en/stable/quickstart/ - - diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/Flask-1.1.2.dist-info/RECORD b/Jobs_Collections/venv/Lib/python3.8/site-packages/Flask-1.1.2.dist-info/RECORD deleted file mode 100644 index 7098140..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/Flask-1.1.2.dist-info/RECORD +++ /dev/null @@ -1,48 +0,0 @@ -../../../bin/flask,sha256=7sMFt4F34SuIhj1mBGO_YWBlZ0cTI3mgQBFxgTwmAIA,250 -Flask-1.1.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 -Flask-1.1.2.dist-info/LICENSE.rst,sha256=SJqOEQhQntmKN7uYPhHg9-HTHwvY-Zp5yESOf_N9B-o,1475 -Flask-1.1.2.dist-info/METADATA,sha256=3INpPWH6nKfZ33R2N-bQZy4TOe1wQCMweZc9mwcNrtc,4591 -Flask-1.1.2.dist-info/RECORD,, -Flask-1.1.2.dist-info/WHEEL,sha256=8zNYZbwQSXoB9IfXOjPfeNwvAsALAjffgk27FqvCWbo,110 -Flask-1.1.2.dist-info/entry_points.txt,sha256=gBLA1aKg0OYR8AhbAfg8lnburHtKcgJLDU52BBctN0k,42 -Flask-1.1.2.dist-info/top_level.txt,sha256=dvi65F6AeGWVU0TBpYiC04yM60-FX1gJFkK31IKQr5c,6 -flask/__init__.py,sha256=YnA9wkwbJcnb_jTT-nMsMFeFE_UWt33khKzdHmMSuyI,1894 -flask/__main__.py,sha256=fjVtt3QTANXlpJCOv3Ha7d5H-76MwzSIOab7SFD9TEk,254 -flask/__pycache__/__init__.cpython-38.pyc,, -flask/__pycache__/__main__.cpython-38.pyc,, -flask/__pycache__/_compat.cpython-38.pyc,, -flask/__pycache__/app.cpython-38.pyc,, -flask/__pycache__/blueprints.cpython-38.pyc,, -flask/__pycache__/cli.cpython-38.pyc,, -flask/__pycache__/config.cpython-38.pyc,, -flask/__pycache__/ctx.cpython-38.pyc,, -flask/__pycache__/debughelpers.cpython-38.pyc,, -flask/__pycache__/globals.cpython-38.pyc,, -flask/__pycache__/helpers.cpython-38.pyc,, -flask/__pycache__/logging.cpython-38.pyc,, -flask/__pycache__/sessions.cpython-38.pyc,, -flask/__pycache__/signals.cpython-38.pyc,, -flask/__pycache__/templating.cpython-38.pyc,, -flask/__pycache__/testing.cpython-38.pyc,, -flask/__pycache__/views.cpython-38.pyc,, -flask/__pycache__/wrappers.cpython-38.pyc,, -flask/_compat.py,sha256=8KPT54Iig96TuLipdogLRHNYToIcg-xPhnSV5VRERnw,4099 -flask/app.py,sha256=tmEhx_XrIRP24vZg39dHMWFzJ2jj-YxIcd51LaIT5cE,98059 -flask/blueprints.py,sha256=vkdm8NusGsfZUeIfPdCluj733QFmiQcT4Sk1tuZLUjw,21400 -flask/cli.py,sha256=SIb22uq9wYBeB2tKMl0pYdhtZ1MAQyZtPL-3m6es4G0,31035 -flask/config.py,sha256=3dejvQRYfNHw_V7dCLMxU8UNFpL34xIKemN7gHZIZ8Y,10052 -flask/ctx.py,sha256=cks-omGedkxawHFo6bKIrdOHsJCAgg1i_NWw_htxb5U,16724 -flask/debughelpers.py,sha256=-whvPKuAoU8AZ9c1z_INuOeBgfYDqE1J2xNBsoriugU,6475 -flask/globals.py,sha256=OgcHb6_NCyX6-TldciOdKcyj4PNfyQwClxdMhvov6aA,1637 -flask/helpers.py,sha256=IHa578HU_3XAAo1wpXQv24MYRYO5TzaiDQQwvUIcE6Q,43074 -flask/json/__init__.py,sha256=6nITbZYiYOPB8Qfi1-dvsblwn01KRz8VOsMBIZyaYek,11988 -flask/json/__pycache__/__init__.cpython-38.pyc,, -flask/json/__pycache__/tag.cpython-38.pyc,, -flask/json/tag.py,sha256=vq9GOllg_0kTWKuVFrwmkeOQzR-jdBD23x-89JyCCQI,8306 -flask/logging.py,sha256=WcY5UkqTysGfmosyygSlXyZYGwOp3y-VsE6ehoJ48dk,3250 -flask/sessions.py,sha256=G0KsEkr_i1LG_wOINwFSOW3ts7Xbv4bNgEZKc7TRloc,14360 -flask/signals.py,sha256=yYLOed2x8WnQ7pirGalQYfpYpCILJ0LJhmNSrnWvjqw,2212 -flask/templating.py,sha256=F8E_IZXn9BGsjMzUJ5N_ACMyZdiFBp_SSEaUunvfZ7g,4939 -flask/testing.py,sha256=WXsciCQbHBP7xjHqNvOA4bT0k86GvSNpgzncfXLDEEg,10146 -flask/views.py,sha256=eeWnadLAj0QdQPLtjKipDetRZyG62CT2y7fNOFDJz0g,5802 -flask/wrappers.py,sha256=kgsvtZuMM6RQaDqhRbc5Pcj9vqTnaERl2pmXcdGL7LU,4736 diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/Flask-1.1.2.dist-info/WHEEL b/Jobs_Collections/venv/Lib/python3.8/site-packages/Flask-1.1.2.dist-info/WHEEL deleted file mode 100644 index 8b701e9..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/Flask-1.1.2.dist-info/WHEEL +++ /dev/null @@ -1,6 +0,0 @@ -Wheel-Version: 1.0 -Generator: bdist_wheel (0.33.6) -Root-Is-Purelib: true -Tag: py2-none-any -Tag: py3-none-any - diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/Flask-1.1.2.dist-info/entry_points.txt b/Jobs_Collections/venv/Lib/python3.8/site-packages/Flask-1.1.2.dist-info/entry_points.txt deleted file mode 100644 index 1eb0252..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/Flask-1.1.2.dist-info/entry_points.txt +++ /dev/null @@ -1,3 +0,0 @@ -[console_scripts] -flask = flask.cli:main - diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/Flask-1.1.2.dist-info/top_level.txt b/Jobs_Collections/venv/Lib/python3.8/site-packages/Flask-1.1.2.dist-info/top_level.txt deleted file mode 100644 index 7e10602..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/Flask-1.1.2.dist-info/top_level.txt +++ /dev/null @@ -1 +0,0 @@ -flask diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/Jinja2-2.11.2.dist-info/INSTALLER b/Jobs_Collections/venv/Lib/python3.8/site-packages/Jinja2-2.11.2.dist-info/INSTALLER deleted file mode 100644 index a1b589e..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/Jinja2-2.11.2.dist-info/INSTALLER +++ /dev/null @@ -1 +0,0 @@ -pip diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/Jinja2-2.11.2.dist-info/LICENSE.rst b/Jobs_Collections/venv/Lib/python3.8/site-packages/Jinja2-2.11.2.dist-info/LICENSE.rst deleted file mode 100644 index c37cae4..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/Jinja2-2.11.2.dist-info/LICENSE.rst +++ /dev/null @@ -1,28 +0,0 @@ -Copyright 2007 Pallets - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - -1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - -2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - -3. Neither the name of the copyright holder nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A -PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/Jinja2-2.11.2.dist-info/METADATA b/Jobs_Collections/venv/Lib/python3.8/site-packages/Jinja2-2.11.2.dist-info/METADATA deleted file mode 100644 index 55c0f82..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/Jinja2-2.11.2.dist-info/METADATA +++ /dev/null @@ -1,106 +0,0 @@ -Metadata-Version: 2.1 -Name: Jinja2 -Version: 2.11.2 -Summary: A very fast and expressive template engine. -Home-page: https://palletsprojects.com/p/jinja/ -Author: Armin Ronacher -Author-email: armin.ronacher@active-4.com -Maintainer: Pallets -Maintainer-email: contact@palletsprojects.com -License: BSD-3-Clause -Project-URL: Documentation, https://jinja.palletsprojects.com/ -Project-URL: Code, https://github.com/pallets/jinja -Project-URL: Issue tracker, https://github.com/pallets/jinja/issues -Platform: UNKNOWN -Classifier: Development Status :: 5 - Production/Stable -Classifier: Environment :: Web Environment -Classifier: Intended Audience :: Developers -Classifier: License :: OSI Approved :: BSD License -Classifier: Operating System :: OS Independent -Classifier: Programming Language :: Python -Classifier: Programming Language :: Python :: 2 -Classifier: Programming Language :: Python :: 2.7 -Classifier: Programming Language :: Python :: 3 -Classifier: Programming Language :: Python :: 3.5 -Classifier: Programming Language :: Python :: 3.6 -Classifier: Programming Language :: Python :: 3.7 -Classifier: Programming Language :: Python :: 3.8 -Classifier: Programming Language :: Python :: Implementation :: CPython -Classifier: Programming Language :: Python :: Implementation :: PyPy -Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content -Classifier: Topic :: Software Development :: Libraries :: Python Modules -Classifier: Topic :: Text Processing :: Markup :: HTML -Requires-Python: >=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.* -Description-Content-Type: text/x-rst -Requires-Dist: MarkupSafe (>=0.23) -Provides-Extra: i18n -Requires-Dist: Babel (>=0.8) ; extra == 'i18n' - -Jinja -===== - -Jinja is a fast, expressive, extensible templating engine. Special -placeholders in the template allow writing code similar to Python -syntax. Then the template is passed data to render the final document. - -It includes: - -- Template inheritance and inclusion. -- Define and import macros within templates. -- HTML templates can use autoescaping to prevent XSS from untrusted - user input. -- A sandboxed environment can safely render untrusted templates. -- AsyncIO support for generating templates and calling async - functions. -- I18N support with Babel. -- Templates are compiled to optimized Python code just-in-time and - cached, or can be compiled ahead-of-time. -- Exceptions point to the correct line in templates to make debugging - easier. -- Extensible filters, tests, functions, and even syntax. - -Jinja's philosophy is that while application logic belongs in Python if -possible, it shouldn't make the template designer's job difficult by -restricting functionality too much. - - -Installing ----------- - -Install and update using `pip`_: - -.. code-block:: text - - $ pip install -U Jinja2 - -.. _pip: https://pip.pypa.io/en/stable/quickstart/ - - -In A Nutshell -------------- - -.. code-block:: jinja - - {% extends "base.html" %} - {% block title %}Members{% endblock %} - {% block content %} - - {% endblock %} - - -Links ------ - -- Website: https://palletsprojects.com/p/jinja/ -- Documentation: https://jinja.palletsprojects.com/ -- Releases: https://pypi.org/project/Jinja2/ -- Code: https://github.com/pallets/jinja -- Issue tracker: https://github.com/pallets/jinja/issues -- Test status: https://dev.azure.com/pallets/jinja/_build -- Official chat: https://discord.gg/t6rrQZH - - diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/Jinja2-2.11.2.dist-info/RECORD b/Jobs_Collections/venv/Lib/python3.8/site-packages/Jinja2-2.11.2.dist-info/RECORD deleted file mode 100644 index d1a691f..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/Jinja2-2.11.2.dist-info/RECORD +++ /dev/null @@ -1,61 +0,0 @@ -Jinja2-2.11.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 -Jinja2-2.11.2.dist-info/LICENSE.rst,sha256=O0nc7kEF6ze6wQ-vG-JgQI_oXSUrjp3y4JefweCUQ3s,1475 -Jinja2-2.11.2.dist-info/METADATA,sha256=5ZHRZoIRAMHsJPnqhlJ622_dRPsYePYJ-9EH4-Ry7yI,3535 -Jinja2-2.11.2.dist-info/RECORD,, -Jinja2-2.11.2.dist-info/WHEEL,sha256=kGT74LWyRUZrL4VgLh6_g12IeVl_9u9ZVhadrgXZUEY,110 -Jinja2-2.11.2.dist-info/entry_points.txt,sha256=Qy_DkVo6Xj_zzOtmErrATe8lHZhOqdjpt3e4JJAGyi8,61 -Jinja2-2.11.2.dist-info/top_level.txt,sha256=PkeVWtLb3-CqjWi1fO29OCbj55EhX_chhKrCdrVe_zs,7 -jinja2/__init__.py,sha256=0QCM_jKKDM10yzSdHRVV4mQbCbDqf0GN0GirAqibn9Y,1549 -jinja2/__pycache__/__init__.cpython-38.pyc,, -jinja2/__pycache__/_compat.cpython-38.pyc,, -jinja2/__pycache__/_identifier.cpython-38.pyc,, -jinja2/__pycache__/asyncfilters.cpython-38.pyc,, -jinja2/__pycache__/asyncsupport.cpython-38.pyc,, -jinja2/__pycache__/bccache.cpython-38.pyc,, -jinja2/__pycache__/compiler.cpython-38.pyc,, -jinja2/__pycache__/constants.cpython-38.pyc,, -jinja2/__pycache__/debug.cpython-38.pyc,, -jinja2/__pycache__/defaults.cpython-38.pyc,, -jinja2/__pycache__/environment.cpython-38.pyc,, -jinja2/__pycache__/exceptions.cpython-38.pyc,, -jinja2/__pycache__/ext.cpython-38.pyc,, -jinja2/__pycache__/filters.cpython-38.pyc,, -jinja2/__pycache__/idtracking.cpython-38.pyc,, -jinja2/__pycache__/lexer.cpython-38.pyc,, -jinja2/__pycache__/loaders.cpython-38.pyc,, -jinja2/__pycache__/meta.cpython-38.pyc,, -jinja2/__pycache__/nativetypes.cpython-38.pyc,, -jinja2/__pycache__/nodes.cpython-38.pyc,, -jinja2/__pycache__/optimizer.cpython-38.pyc,, -jinja2/__pycache__/parser.cpython-38.pyc,, -jinja2/__pycache__/runtime.cpython-38.pyc,, -jinja2/__pycache__/sandbox.cpython-38.pyc,, -jinja2/__pycache__/tests.cpython-38.pyc,, -jinja2/__pycache__/utils.cpython-38.pyc,, -jinja2/__pycache__/visitor.cpython-38.pyc,, -jinja2/_compat.py,sha256=B6Se8HjnXVpzz9-vfHejn-DV2NjaVK-Iewupc5kKlu8,3191 -jinja2/_identifier.py,sha256=EdgGJKi7O1yvr4yFlvqPNEqV6M1qHyQr8Gt8GmVTKVM,1775 -jinja2/asyncfilters.py,sha256=XJtYXTxFvcJ5xwk6SaDL4S0oNnT0wPYvXBCSzc482fI,4250 -jinja2/asyncsupport.py,sha256=ZBFsDLuq3Gtji3Ia87lcyuDbqaHZJRdtShZcqwpFnSQ,7209 -jinja2/bccache.py,sha256=3Pmp4jo65M9FQuIxdxoDBbEDFwe4acDMQf77nEJfrHA,12139 -jinja2/compiler.py,sha256=Ta9W1Lit542wItAHXlDcg0sEOsFDMirCdlFPHAurg4o,66284 -jinja2/constants.py,sha256=RR1sTzNzUmKco6aZicw4JpQpJGCuPuqm1h1YmCNUEFY,1458 -jinja2/debug.py,sha256=neR7GIGGjZH3_ILJGVUYy3eLQCCaWJMXOb7o0kGInWc,8529 -jinja2/defaults.py,sha256=85B6YUUCyWPSdrSeVhcqFVuu_bHUAQXeey--FIwSeVQ,1126 -jinja2/environment.py,sha256=XDSLKc4SqNLMOwTSq3TbWEyA5WyXfuLuVD0wAVjEFwM,50629 -jinja2/exceptions.py,sha256=VjNLawcmf2ODffqVMCQK1cRmvFaUfQWF4u8ouP3QPcE,5425 -jinja2/ext.py,sha256=AtwL5O5enT_L3HR9-oBvhGyUTdGoyaqG_ICtnR_EVd4,26441 -jinja2/filters.py,sha256=_RpPgAlgIj7ExvyDzcHAC3B36cocfWK-1TEketbNeM0,41415 -jinja2/idtracking.py,sha256=J3O4VHsrbf3wzwiBc7Cro26kHb6_5kbULeIOzocchIU,9211 -jinja2/lexer.py,sha256=nUFLRKhhKmmEWkLI65nQePgcQs7qsRdjVYZETMt_v0g,30331 -jinja2/loaders.py,sha256=C-fST_dmFjgWkp0ZuCkrgICAoOsoSIF28wfAFink0oU,17666 -jinja2/meta.py,sha256=QjyYhfNRD3QCXjBJpiPl9KgkEkGXJbAkCUq4-Ur10EQ,4131 -jinja2/nativetypes.py,sha256=Ul__gtVw4xH-0qvUvnCNHedQeNDwmEuyLJztzzSPeRg,2753 -jinja2/nodes.py,sha256=Mk1oJPVgIjnQw9WOqILvcu3rLepcFZ0ahxQm2mbwDwc,31095 -jinja2/optimizer.py,sha256=gQLlMYzvQhluhzmAIFA1tXS0cwgWYOjprN-gTRcHVsc,1457 -jinja2/parser.py,sha256=fcfdqePNTNyvosIvczbytVA332qpsURvYnCGcjDHSkA,35660 -jinja2/runtime.py,sha256=0y-BRyIEZ9ltByL2Id6GpHe1oDRQAwNeQvI0SKobNMw,30618 -jinja2/sandbox.py,sha256=knayyUvXsZ-F0mk15mO2-ehK9gsw04UhB8td-iUOtLc,17127 -jinja2/tests.py,sha256=iO_Y-9Vo60zrVe1lMpSl5sKHqAxe2leZHC08OoZ8K24,4799 -jinja2/utils.py,sha256=OoVMlQe9S2-lWT6jJbTu9tDuDvGNyWUhHDcE51i5_Do,22522 -jinja2/visitor.py,sha256=DUHupl0a4PGp7nxRtZFttUzAi1ccxzqc2hzetPYUz8U,3240 diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/Jinja2-2.11.2.dist-info/WHEEL b/Jobs_Collections/venv/Lib/python3.8/site-packages/Jinja2-2.11.2.dist-info/WHEEL deleted file mode 100644 index ef99c6c..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/Jinja2-2.11.2.dist-info/WHEEL +++ /dev/null @@ -1,6 +0,0 @@ -Wheel-Version: 1.0 -Generator: bdist_wheel (0.34.2) -Root-Is-Purelib: true -Tag: py2-none-any -Tag: py3-none-any - diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/Jinja2-2.11.2.dist-info/entry_points.txt b/Jobs_Collections/venv/Lib/python3.8/site-packages/Jinja2-2.11.2.dist-info/entry_points.txt deleted file mode 100644 index 3619483..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/Jinja2-2.11.2.dist-info/entry_points.txt +++ /dev/null @@ -1,3 +0,0 @@ -[babel.extractors] -jinja2 = jinja2.ext:babel_extract [i18n] - diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/Jinja2-2.11.2.dist-info/top_level.txt b/Jobs_Collections/venv/Lib/python3.8/site-packages/Jinja2-2.11.2.dist-info/top_level.txt deleted file mode 100644 index 7f7afbf..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/Jinja2-2.11.2.dist-info/top_level.txt +++ /dev/null @@ -1 +0,0 @@ -jinja2 diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/MarkupSafe-1.1.1.dist-info/INSTALLER b/Jobs_Collections/venv/Lib/python3.8/site-packages/MarkupSafe-1.1.1.dist-info/INSTALLER deleted file mode 100644 index a1b589e..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/MarkupSafe-1.1.1.dist-info/INSTALLER +++ /dev/null @@ -1 +0,0 @@ -pip diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/MarkupSafe-1.1.1.dist-info/LICENSE.rst b/Jobs_Collections/venv/Lib/python3.8/site-packages/MarkupSafe-1.1.1.dist-info/LICENSE.rst deleted file mode 100644 index 9d227a0..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/MarkupSafe-1.1.1.dist-info/LICENSE.rst +++ /dev/null @@ -1,28 +0,0 @@ -Copyright 2010 Pallets - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - -1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - -2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - -3. Neither the name of the copyright holder nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A -PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/MarkupSafe-1.1.1.dist-info/METADATA b/Jobs_Collections/venv/Lib/python3.8/site-packages/MarkupSafe-1.1.1.dist-info/METADATA deleted file mode 100644 index c50370d..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/MarkupSafe-1.1.1.dist-info/METADATA +++ /dev/null @@ -1,105 +0,0 @@ -Metadata-Version: 2.1 -Name: MarkupSafe -Version: 1.1.1 -Summary: Safely add untrusted strings to HTML/XML markup. -Home-page: https://palletsprojects.com/p/markupsafe/ -Author: Armin Ronacher -Author-email: armin.ronacher@active-4.com -Maintainer: The Pallets Team -Maintainer-email: contact@palletsprojects.com -License: BSD-3-Clause -Project-URL: Documentation, https://markupsafe.palletsprojects.com/ -Project-URL: Code, https://github.com/pallets/markupsafe -Project-URL: Issue tracker, https://github.com/pallets/markupsafe/issues -Platform: UNKNOWN -Classifier: Development Status :: 5 - Production/Stable -Classifier: Environment :: Web Environment -Classifier: Intended Audience :: Developers -Classifier: License :: OSI Approved :: BSD License -Classifier: Operating System :: OS Independent -Classifier: Programming Language :: Python -Classifier: Programming Language :: Python :: 2 -Classifier: Programming Language :: Python :: 2.7 -Classifier: Programming Language :: Python :: 3 -Classifier: Programming Language :: Python :: 3.4 -Classifier: Programming Language :: Python :: 3.5 -Classifier: Programming Language :: Python :: 3.6 -Classifier: Programming Language :: Python :: 3.7 -Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content -Classifier: Topic :: Software Development :: Libraries :: Python Modules -Classifier: Topic :: Text Processing :: Markup :: HTML -Requires-Python: >=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.* -Description-Content-Type: text/x-rst - -MarkupSafe -========== - -MarkupSafe implements a text object that escapes characters so it is -safe to use in HTML and XML. Characters that have special meanings are -replaced so that they display as the actual characters. This mitigates -injection attacks, meaning untrusted user input can safely be displayed -on a page. - - -Installing ----------- - -Install and update using `pip`_: - -.. code-block:: text - - pip install -U MarkupSafe - -.. _pip: https://pip.pypa.io/en/stable/quickstart/ - - -Examples --------- - -.. code-block:: pycon - - >>> from markupsafe import Markup, escape - >>> # escape replaces special characters and wraps in Markup - >>> escape('') - Markup(u'<script>alert(document.cookie);</script>') - >>> # wrap in Markup to mark text "safe" and prevent escaping - >>> Markup('Hello') - Markup('hello') - >>> escape(Markup('Hello')) - Markup('hello') - >>> # Markup is a text subclass (str on Python 3, unicode on Python 2) - >>> # methods and operators escape their arguments - >>> template = Markup("Hello %s") - >>> template % '"World"' - Markup('Hello "World"') - - -Donate ------- - -The Pallets organization develops and supports MarkupSafe and other -libraries that use it. In order to grow the community of contributors -and users, and allow the maintainers to devote more time to the -projects, `please donate today`_. - -.. _please donate today: https://palletsprojects.com/donate - - -Links ------ - -* Website: https://palletsprojects.com/p/markupsafe/ -* Documentation: https://markupsafe.palletsprojects.com/ -* License: `BSD-3-Clause `_ -* Releases: https://pypi.org/project/MarkupSafe/ -* Code: https://github.com/pallets/markupsafe -* Issue tracker: https://github.com/pallets/markupsafe/issues -* Test status: - - * Linux, Mac: https://travis-ci.org/pallets/markupsafe - * Windows: https://ci.appveyor.com/project/pallets/markupsafe - -* Test coverage: https://codecov.io/gh/pallets/markupsafe -* Official chat: https://discord.gg/t6rrQZH - - diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/MarkupSafe-1.1.1.dist-info/RECORD b/Jobs_Collections/venv/Lib/python3.8/site-packages/MarkupSafe-1.1.1.dist-info/RECORD deleted file mode 100644 index 1b2c700..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/MarkupSafe-1.1.1.dist-info/RECORD +++ /dev/null @@ -1,16 +0,0 @@ -MarkupSafe-1.1.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 -MarkupSafe-1.1.1.dist-info/LICENSE.rst,sha256=SJqOEQhQntmKN7uYPhHg9-HTHwvY-Zp5yESOf_N9B-o,1475 -MarkupSafe-1.1.1.dist-info/METADATA,sha256=IFCP4hCNGjXJgMoSvdjPiKDLAMUTTWoxKXQsQvmyMNU,3653 -MarkupSafe-1.1.1.dist-info/RECORD,, -MarkupSafe-1.1.1.dist-info/WHEEL,sha256=Q2jwauV7SdXlb20cz-bh9vn-BQ4tlA1IGNkj_GWnse8,109 -MarkupSafe-1.1.1.dist-info/top_level.txt,sha256=qy0Plje5IJuvsCBjejJyhDCjEAdcDLK_2agVcex8Z6U,11 -markupsafe/__init__.py,sha256=oTblO5f9KFM-pvnq9bB0HgElnqkJyqHnFN1Nx2NIvnY,10126 -markupsafe/__pycache__/__init__.cpython-38.pyc,, -markupsafe/__pycache__/_compat.cpython-38.pyc,, -markupsafe/__pycache__/_constants.cpython-38.pyc,, -markupsafe/__pycache__/_native.cpython-38.pyc,, -markupsafe/_compat.py,sha256=uEW1ybxEjfxIiuTbRRaJpHsPFf4yQUMMKaPgYEC5XbU,558 -markupsafe/_constants.py,sha256=zo2ajfScG-l1Sb_52EP3MlDCqO7Y1BVHUXXKRsVDRNk,4690 -markupsafe/_native.py,sha256=d-8S_zzYt2y512xYcuSxq0NeG2DUUvG80wVdTn-4KI8,1873 -markupsafe/_speedups.c,sha256=k0fzEIK3CP6MmMqeY0ob43TP90mVN0DTyn7BAl3RqSg,9884 -markupsafe/_speedups.cpython-38-darwin.so,sha256=X3mbW9ZrEJiuX0l5D69_hOpCXJkeTmPdhuiCHy5iCZc,14744 diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/MarkupSafe-1.1.1.dist-info/WHEEL b/Jobs_Collections/venv/Lib/python3.8/site-packages/MarkupSafe-1.1.1.dist-info/WHEEL deleted file mode 100644 index f7c2100..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/MarkupSafe-1.1.1.dist-info/WHEEL +++ /dev/null @@ -1,5 +0,0 @@ -Wheel-Version: 1.0 -Generator: bdist_wheel (0.33.6) -Root-Is-Purelib: false -Tag: cp38-cp38-macosx_10_9_x86_64 - diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/MarkupSafe-1.1.1.dist-info/top_level.txt b/Jobs_Collections/venv/Lib/python3.8/site-packages/MarkupSafe-1.1.1.dist-info/top_level.txt deleted file mode 100644 index 75bf729..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/MarkupSafe-1.1.1.dist-info/top_level.txt +++ /dev/null @@ -1 +0,0 @@ -markupsafe diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/Werkzeug-1.0.1.dist-info/INSTALLER b/Jobs_Collections/venv/Lib/python3.8/site-packages/Werkzeug-1.0.1.dist-info/INSTALLER deleted file mode 100644 index a1b589e..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/Werkzeug-1.0.1.dist-info/INSTALLER +++ /dev/null @@ -1 +0,0 @@ -pip diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/Werkzeug-1.0.1.dist-info/LICENSE.rst b/Jobs_Collections/venv/Lib/python3.8/site-packages/Werkzeug-1.0.1.dist-info/LICENSE.rst deleted file mode 100644 index c37cae4..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/Werkzeug-1.0.1.dist-info/LICENSE.rst +++ /dev/null @@ -1,28 +0,0 @@ -Copyright 2007 Pallets - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - -1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - -2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - -3. Neither the name of the copyright holder nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A -PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/Werkzeug-1.0.1.dist-info/METADATA b/Jobs_Collections/venv/Lib/python3.8/site-packages/Werkzeug-1.0.1.dist-info/METADATA deleted file mode 100644 index eb5f709..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/Werkzeug-1.0.1.dist-info/METADATA +++ /dev/null @@ -1,128 +0,0 @@ -Metadata-Version: 2.1 -Name: Werkzeug -Version: 1.0.1 -Summary: The comprehensive WSGI web application library. -Home-page: https://palletsprojects.com/p/werkzeug/ -Author: Armin Ronacher -Author-email: armin.ronacher@active-4.com -Maintainer: Pallets -Maintainer-email: contact@palletsprojects.com -License: BSD-3-Clause -Project-URL: Documentation, https://werkzeug.palletsprojects.com/ -Project-URL: Code, https://github.com/pallets/werkzeug -Project-URL: Issue tracker, https://github.com/pallets/werkzeug/issues -Platform: UNKNOWN -Classifier: Development Status :: 5 - Production/Stable -Classifier: Environment :: Web Environment -Classifier: Intended Audience :: Developers -Classifier: License :: OSI Approved :: BSD License -Classifier: Operating System :: OS Independent -Classifier: Programming Language :: Python -Classifier: Programming Language :: Python :: 2 -Classifier: Programming Language :: Python :: 2.7 -Classifier: Programming Language :: Python :: 3 -Classifier: Programming Language :: Python :: 3.5 -Classifier: Programming Language :: Python :: 3.6 -Classifier: Programming Language :: Python :: 3.7 -Classifier: Programming Language :: Python :: 3.8 -Classifier: Programming Language :: Python :: Implementation :: CPython -Classifier: Programming Language :: Python :: Implementation :: PyPy -Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content -Classifier: Topic :: Internet :: WWW/HTTP :: WSGI -Classifier: Topic :: Internet :: WWW/HTTP :: WSGI :: Application -Classifier: Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware -Classifier: Topic :: Software Development :: Libraries :: Application Frameworks -Classifier: Topic :: Software Development :: Libraries :: Python Modules -Requires-Python: >=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.* -Description-Content-Type: text/x-rst -Provides-Extra: dev -Requires-Dist: pytest ; extra == 'dev' -Requires-Dist: pytest-timeout ; extra == 'dev' -Requires-Dist: coverage ; extra == 'dev' -Requires-Dist: tox ; extra == 'dev' -Requires-Dist: sphinx ; extra == 'dev' -Requires-Dist: pallets-sphinx-themes ; extra == 'dev' -Requires-Dist: sphinx-issues ; extra == 'dev' -Provides-Extra: watchdog -Requires-Dist: watchdog ; extra == 'watchdog' - -Werkzeug -======== - -*werkzeug* German noun: "tool". Etymology: *werk* ("work"), *zeug* ("stuff") - -Werkzeug is a comprehensive `WSGI`_ web application library. It began as -a simple collection of various utilities for WSGI applications and has -become one of the most advanced WSGI utility libraries. - -It includes: - -- An interactive debugger that allows inspecting stack traces and - source code in the browser with an interactive interpreter for any - frame in the stack. -- A full-featured request object with objects to interact with - headers, query args, form data, files, and cookies. -- A response object that can wrap other WSGI applications and handle - streaming data. -- A routing system for matching URLs to endpoints and generating URLs - for endpoints, with an extensible system for capturing variables - from URLs. -- HTTP utilities to handle entity tags, cache control, dates, user - agents, cookies, files, and more. -- A threaded WSGI server for use while developing applications - locally. -- A test client for simulating HTTP requests during testing without - requiring running a server. - -Werkzeug is Unicode aware and doesn't enforce any dependencies. It is up -to the developer to choose a template engine, database adapter, and even -how to handle requests. It can be used to build all sorts of end user -applications such as blogs, wikis, or bulletin boards. - -`Flask`_ wraps Werkzeug, using it to handle the details of WSGI while -providing more structure and patterns for defining powerful -applications. - - -Installing ----------- - -Install and update using `pip`_: - -.. code-block:: text - - pip install -U Werkzeug - - -A Simple Example ----------------- - -.. code-block:: python - - from werkzeug.wrappers import Request, Response - - @Request.application - def application(request): - return Response('Hello, World!') - - if __name__ == '__main__': - from werkzeug.serving import run_simple - run_simple('localhost', 4000, application) - - -Links ------ - -- Website: https://palletsprojects.com/p/werkzeug/ -- Documentation: https://werkzeug.palletsprojects.com/ -- Releases: https://pypi.org/project/Werkzeug/ -- Code: https://github.com/pallets/werkzeug -- Issue tracker: https://github.com/pallets/werkzeug/issues -- Test status: https://dev.azure.com/pallets/werkzeug/_build -- Official chat: https://discord.gg/t6rrQZH - -.. _WSGI: https://wsgi.readthedocs.io/en/latest/ -.. _Flask: https://www.palletsprojects.com/p/flask/ -.. _pip: https://pip.pypa.io/en/stable/quickstart/ - - diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/Werkzeug-1.0.1.dist-info/RECORD b/Jobs_Collections/venv/Lib/python3.8/site-packages/Werkzeug-1.0.1.dist-info/RECORD deleted file mode 100644 index 9bc5975..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/Werkzeug-1.0.1.dist-info/RECORD +++ /dev/null @@ -1,101 +0,0 @@ -Werkzeug-1.0.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 -Werkzeug-1.0.1.dist-info/LICENSE.rst,sha256=O0nc7kEF6ze6wQ-vG-JgQI_oXSUrjp3y4JefweCUQ3s,1475 -Werkzeug-1.0.1.dist-info/METADATA,sha256=d0zmVNa4UC2-nAo2A8_81oiy123D6JTGRSuY_Ymgyt4,4730 -Werkzeug-1.0.1.dist-info/RECORD,, -Werkzeug-1.0.1.dist-info/WHEEL,sha256=kGT74LWyRUZrL4VgLh6_g12IeVl_9u9ZVhadrgXZUEY,110 -Werkzeug-1.0.1.dist-info/top_level.txt,sha256=QRyj2VjwJoQkrwjwFIOlB8Xg3r9un0NtqVHQF-15xaw,9 -werkzeug/__init__.py,sha256=rb-yPiXOjTLbtDOl5fQp5hN7oBdaoXAoQ-slAAvfZAo,502 -werkzeug/__pycache__/__init__.cpython-38.pyc,, -werkzeug/__pycache__/_compat.cpython-38.pyc,, -werkzeug/__pycache__/_internal.cpython-38.pyc,, -werkzeug/__pycache__/_reloader.cpython-38.pyc,, -werkzeug/__pycache__/datastructures.cpython-38.pyc,, -werkzeug/__pycache__/exceptions.cpython-38.pyc,, -werkzeug/__pycache__/filesystem.cpython-38.pyc,, -werkzeug/__pycache__/formparser.cpython-38.pyc,, -werkzeug/__pycache__/http.cpython-38.pyc,, -werkzeug/__pycache__/local.cpython-38.pyc,, -werkzeug/__pycache__/posixemulation.cpython-38.pyc,, -werkzeug/__pycache__/routing.cpython-38.pyc,, -werkzeug/__pycache__/security.cpython-38.pyc,, -werkzeug/__pycache__/serving.cpython-38.pyc,, -werkzeug/__pycache__/test.cpython-38.pyc,, -werkzeug/__pycache__/testapp.cpython-38.pyc,, -werkzeug/__pycache__/urls.cpython-38.pyc,, -werkzeug/__pycache__/useragents.cpython-38.pyc,, -werkzeug/__pycache__/utils.cpython-38.pyc,, -werkzeug/__pycache__/wsgi.cpython-38.pyc,, -werkzeug/_compat.py,sha256=zjufTNrhQ8BgYSGSh-sVu6iW3r3O9WzjE9j-qJobx-g,6671 -werkzeug/_internal.py,sha256=d_4AqheyS6dHMViwdc0drFrjs67ZzT6Ej2gWf-Z-Iys,14351 -werkzeug/_reloader.py,sha256=I3mg3oRQ0lLzl06oEoVopN3bN7CtINuuUQdqDcmTnEs,11531 -werkzeug/datastructures.py,sha256=AonxOcwU0TPMEzfKF1368ySULxHgxE-JE-DEAGdo2ts,100480 -werkzeug/debug/__init__.py,sha256=3RtUMc5Y9hYyK11ugHltgkQ9Dt-ViR945Vy_X5NV7zU,17289 -werkzeug/debug/__pycache__/__init__.cpython-38.pyc,, -werkzeug/debug/__pycache__/console.cpython-38.pyc,, -werkzeug/debug/__pycache__/repr.cpython-38.pyc,, -werkzeug/debug/__pycache__/tbtools.cpython-38.pyc,, -werkzeug/debug/console.py,sha256=OATaO7KHYMqpbzIFe1HeW9Mnl3wZgA3jMQoGDPn5URc,5488 -werkzeug/debug/repr.py,sha256=lIwuhbyrMwVe3P_cFqNyqzHL7P93TLKod7lw9clydEw,9621 -werkzeug/debug/shared/FONT_LICENSE,sha256=LwAVEI1oYnvXiNMT9SnCH_TaLCxCpeHziDrMg0gPkAI,4673 -werkzeug/debug/shared/console.png,sha256=bxax6RXXlvOij_KeqvSNX0ojJf83YbnZ7my-3Gx9w2A,507 -werkzeug/debug/shared/debugger.js,sha256=rOhqZMRfpZnnu6_XCGn6wMWPhtfwRAcyZKksdIxPJas,6400 -werkzeug/debug/shared/jquery.js,sha256=CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo,88145 -werkzeug/debug/shared/less.png,sha256=-4-kNRaXJSONVLahrQKUxMwXGm9R4OnZ9SxDGpHlIR4,191 -werkzeug/debug/shared/more.png,sha256=GngN7CioHQoV58rH6ojnkYi8c_qED2Aka5FO5UXrReY,200 -werkzeug/debug/shared/source.png,sha256=RoGcBTE4CyCB85GBuDGTFlAnUqxwTBiIfDqW15EpnUQ,818 -werkzeug/debug/shared/style.css,sha256=gZ9uhmb5zj3XLuT9RvnMp6jMINgQ-VVBCp-2AZbG3YQ,6604 -werkzeug/debug/shared/ubuntu.ttf,sha256=1eaHFyepmy4FyDvjLVzpITrGEBu_CZYY94jE0nED1c0,70220 -werkzeug/debug/tbtools.py,sha256=2iJ8RURUZUSbopOIehy53LnVJWx47lsHN2V2l6hc7Wc,20363 -werkzeug/exceptions.py,sha256=UTYSDkmAsH-vt8VSidlEffwqBVNXuT7bRg-_NqgUe8A,25188 -werkzeug/filesystem.py,sha256=HzKl-j0Hd8Jl66j778UbPTAYNnY6vUZgYLlBZ0e7uw0,2101 -werkzeug/formparser.py,sha256=Sto0jZid9im9ZVIf56vilCdyX-arK33wSftkYsLCnzo,21788 -werkzeug/http.py,sha256=KVRV3yFK14PJeI56qClEq4qxFdvKUQVy4C_dwuWz9_Q,43107 -werkzeug/local.py,sha256=_Tk7gB238pPWUU7habxFkZF02fiCMRVW6d62YWL1Rh0,14371 -werkzeug/middleware/__init__.py,sha256=f1SFZo67IlW4k1uqKzNHxYQlsakUS-D6KK_j0e3jjwQ,549 -werkzeug/middleware/__pycache__/__init__.cpython-38.pyc,, -werkzeug/middleware/__pycache__/dispatcher.cpython-38.pyc,, -werkzeug/middleware/__pycache__/http_proxy.cpython-38.pyc,, -werkzeug/middleware/__pycache__/lint.cpython-38.pyc,, -werkzeug/middleware/__pycache__/profiler.cpython-38.pyc,, -werkzeug/middleware/__pycache__/proxy_fix.cpython-38.pyc,, -werkzeug/middleware/__pycache__/shared_data.cpython-38.pyc,, -werkzeug/middleware/dispatcher.py,sha256=_-KoMzHtcISHS7ouWKAOraqlCLprdh83YOAn_8DjLp8,2240 -werkzeug/middleware/http_proxy.py,sha256=lRjTdMmghHiZuZrS7_UJ3gZc-vlFizhBbFZ-XZPLwIA,7117 -werkzeug/middleware/lint.py,sha256=ItTwuWJnflF8xMT1uqU_Ty1ryhux-CjeUfskqaUpxsw,12967 -werkzeug/middleware/profiler.py,sha256=8B_s23d6BGrU_q54gJsm6kcCbOJbTSqrXCsioHON0Xs,4471 -werkzeug/middleware/proxy_fix.py,sha256=K5oZ3DPXOzdZi0Xba5zW7ClPOxgUuqXHQHvY2-AWCGw,6431 -werkzeug/middleware/shared_data.py,sha256=sPSRTKqtKSVBUyN8fr6jOJbdq9cdOLu6pg3gz4Y_1Xo,9599 -werkzeug/posixemulation.py,sha256=gSSiv1SCmOyzOM_nq1ZaZCtxP__C5MeDJl_4yXJmi4Q,3541 -werkzeug/routing.py,sha256=6-iZ7CKeUILYAehoKXLbmi5E6LgLbwuzUh8TNplnf5Q,79019 -werkzeug/security.py,sha256=81149MplFq7-hD4RK4sKp9kzXXejjV9D4lWBzaRyeQ8,8106 -werkzeug/serving.py,sha256=YvTqvurA-Mnj8mkqRe2kBdVr2ap4ibCq1ByQjOA6g1w,38694 -werkzeug/test.py,sha256=GJ9kxTMSJ-nB7kfGtxuROr9JGmXxDRev-2U1SkeUJGE,39564 -werkzeug/testapp.py,sha256=bHekqMsqRfVxwgFbvOMem-DYa_sdB7R47yUXpt1RUTo,9329 -werkzeug/urls.py,sha256=T8-hV_1vwhu6xhX93FwsHteK-W-kIE2orj5WoMf-WFw,39322 -werkzeug/useragents.py,sha256=TSoGv5IOvP375eK5gLLpsLQCeUgTR6sO1WftmAP_YvM,5563 -werkzeug/utils.py,sha256=hrVK4u_wi8z9viBO9bgOLlm1aaIvCpn-p2d1FeZQDEo,25251 -werkzeug/wrappers/__init__.py,sha256=S4VioKAmF_av9Ec9zQvG71X1EOkYfPx1TYck9jyDiyY,1384 -werkzeug/wrappers/__pycache__/__init__.cpython-38.pyc,, -werkzeug/wrappers/__pycache__/accept.cpython-38.pyc,, -werkzeug/wrappers/__pycache__/auth.cpython-38.pyc,, -werkzeug/wrappers/__pycache__/base_request.cpython-38.pyc,, -werkzeug/wrappers/__pycache__/base_response.cpython-38.pyc,, -werkzeug/wrappers/__pycache__/common_descriptors.cpython-38.pyc,, -werkzeug/wrappers/__pycache__/cors.cpython-38.pyc,, -werkzeug/wrappers/__pycache__/etag.cpython-38.pyc,, -werkzeug/wrappers/__pycache__/json.cpython-38.pyc,, -werkzeug/wrappers/__pycache__/request.cpython-38.pyc,, -werkzeug/wrappers/__pycache__/response.cpython-38.pyc,, -werkzeug/wrappers/__pycache__/user_agent.cpython-38.pyc,, -werkzeug/wrappers/accept.py,sha256=TIvjUc0g73fhTWX54wg_D9NNzKvpnG1X8u1w26tK1o8,1760 -werkzeug/wrappers/auth.py,sha256=Pmn6iaGHBrUyHbJpW0lZhO_q9RVoAa5QalaTqcavdAI,1158 -werkzeug/wrappers/base_request.py,sha256=4TuGlKWeKQdlq4eU94hJYcXSfWo8Rk7CS1Ef5lJ3ZM0,26012 -werkzeug/wrappers/base_response.py,sha256=JTxJZ8o-IBetpoWJqt2HFwPaNWNDAlM3_GXJe1Whw80,27784 -werkzeug/wrappers/common_descriptors.py,sha256=X2Ktd5zUWsmcd4ciaF62Dd8Lru9pLGP_XDUNukc8cXs,12829 -werkzeug/wrappers/cors.py,sha256=XMbaCol4dWTGvb-dCJBoN0p3JX91v93AIAHd7tnB3L4,3466 -werkzeug/wrappers/etag.py,sha256=XMXtyfByBsOjxwaX8U7ZtUY7JXkbQLP45oXZ0qkyTNs,12217 -werkzeug/wrappers/json.py,sha256=HvK_A4NpO0sLqgb10sTJcoZydYOwyNiPCJPV7SVgcgE,4343 -werkzeug/wrappers/request.py,sha256=QbHGqDpGPN684pnOPEokwkPESfm-NnfYM7ydOMxW_NI,1514 -werkzeug/wrappers/response.py,sha256=Oqv8TMG_dnOKTq_V30ddgkO5B7IJhkVPODvm7cbhZ3c,2524 -werkzeug/wrappers/user_agent.py,sha256=YJb-vr12cujG7sQMG9V89VsJa-03SWSenhg1W4cT0EY,435 -werkzeug/wsgi.py,sha256=ZGk85NzRyQTzkYis-xl8V9ydJgfClBdStvhzDzER2mw,34367 diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/Werkzeug-1.0.1.dist-info/WHEEL b/Jobs_Collections/venv/Lib/python3.8/site-packages/Werkzeug-1.0.1.dist-info/WHEEL deleted file mode 100644 index ef99c6c..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/Werkzeug-1.0.1.dist-info/WHEEL +++ /dev/null @@ -1,6 +0,0 @@ -Wheel-Version: 1.0 -Generator: bdist_wheel (0.34.2) -Root-Is-Purelib: true -Tag: py2-none-any -Tag: py3-none-any - diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/Werkzeug-1.0.1.dist-info/top_level.txt b/Jobs_Collections/venv/Lib/python3.8/site-packages/Werkzeug-1.0.1.dist-info/top_level.txt deleted file mode 100644 index 6fe8da8..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/Werkzeug-1.0.1.dist-info/top_level.txt +++ /dev/null @@ -1 +0,0 @@ -werkzeug diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/__pycache__/easy_install.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/__pycache__/easy_install.cpython-38.pyc deleted file mode 100644 index 57e300c..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/__pycache__/easy_install.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/__pycache__/mccabe.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/__pycache__/mccabe.cpython-38.pyc deleted file mode 100644 index 4fdd2b5..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/__pycache__/mccabe.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/__pycache__/six.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/__pycache__/six.cpython-38.pyc deleted file mode 100644 index e4c58e4..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/__pycache__/six.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid-2.4.2.dist-info/COPYING b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid-2.4.2.dist-info/COPYING deleted file mode 100644 index d511905..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid-2.4.2.dist-info/COPYING +++ /dev/null @@ -1,339 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 2, June 1991 - - Copyright (C) 1989, 1991 Free Software Foundation, Inc., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -License is intended to guarantee your freedom to share and change free -software--to make sure the software is free for all its users. This -General Public License applies to most of the Free Software -Foundation's software and to any other program whose authors commit to -using it. (Some other Free Software Foundation software is covered by -the GNU Lesser General Public License instead.) You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -this service if you wish), that you receive source code or can get it -if you want it, that you can change the software or use pieces of it -in new free programs; and that you know you can do these things. - - To protect your rights, we need to make restrictions that forbid -anyone to deny you these rights or to ask you to surrender the rights. -These restrictions translate to certain responsibilities for you if you -distribute copies of the software, or if you modify it. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must give the recipients all the rights that -you have. You must make sure that they, too, receive or can get the -source code. And you must show them these terms so they know their -rights. - - We protect your rights with two steps: (1) copyright the software, and -(2) offer you this license which gives you legal permission to copy, -distribute and/or modify the software. - - Also, for each author's protection and ours, we want to make certain -that everyone understands that there is no warranty for this free -software. If the software is modified by someone else and passed on, we -want its recipients to know that what they have is not the original, so -that any problems introduced by others will not reflect on the original -authors' reputations. - - Finally, any free program is threatened constantly by software -patents. We wish to avoid the danger that redistributors of a free -program will individually obtain patent licenses, in effect making the -program proprietary. To prevent this, we have made it clear that any -patent must be licensed for everyone's free use or not licensed at all. - - The precise terms and conditions for copying, distribution and -modification follow. - - GNU GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License applies to any program or other work which contains -a notice placed by the copyright holder saying it may be distributed -under the terms of this General Public License. The "Program", below, -refers to any such program or work, and a "work based on the Program" -means either the Program or any derivative work under copyright law: -that is to say, a work containing the Program or a portion of it, -either verbatim or with modifications and/or translated into another -language. (Hereinafter, translation is included without limitation in -the term "modification".) Each licensee is addressed as "you". - -Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running the Program is not restricted, and the output from the Program -is covered only if its contents constitute a work based on the -Program (independent of having been made by running the Program). -Whether that is true depends on what the Program does. - - 1. You may copy and distribute verbatim copies of the Program's -source code as you receive it, in any medium, provided that you -conspicuously and appropriately publish on each copy an appropriate -copyright notice and disclaimer of warranty; keep intact all the -notices that refer to this License and to the absence of any warranty; -and give any other recipients of the Program a copy of this License -along with the Program. - -You may charge a fee for the physical act of transferring a copy, and -you may at your option offer warranty protection in exchange for a fee. - - 2. You may modify your copy or copies of the Program or any portion -of it, thus forming a work based on the Program, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) You must cause the modified files to carry prominent notices - stating that you changed the files and the date of any change. - - b) You must cause any work that you distribute or publish, that in - whole or in part contains or is derived from the Program or any - part thereof, to be licensed as a whole at no charge to all third - parties under the terms of this License. - - c) If the modified program normally reads commands interactively - when run, you must cause it, when started running for such - interactive use in the most ordinary way, to print or display an - announcement including an appropriate copyright notice and a - notice that there is no warranty (or else, saying that you provide - a warranty) and that users may redistribute the program under - these conditions, and telling the user how to view a copy of this - License. (Exception: if the Program itself is interactive but - does not normally print such an announcement, your work based on - the Program is not required to print an announcement.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Program, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Program, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Program. - -In addition, mere aggregation of another work not based on the Program -with the Program (or with a work based on the Program) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may copy and distribute the Program (or a work based on it, -under Section 2) in object code or executable form under the terms of -Sections 1 and 2 above provided that you also do one of the following: - - a) Accompany it with the complete corresponding machine-readable - source code, which must be distributed under the terms of Sections - 1 and 2 above on a medium customarily used for software interchange; or, - - b) Accompany it with a written offer, valid for at least three - years, to give any third party, for a charge no more than your - cost of physically performing source distribution, a complete - machine-readable copy of the corresponding source code, to be - distributed under the terms of Sections 1 and 2 above on a medium - customarily used for software interchange; or, - - c) Accompany it with the information you received as to the offer - to distribute corresponding source code. (This alternative is - allowed only for noncommercial distribution and only if you - received the program in object code or executable form with such - an offer, in accord with Subsection b above.) - -The source code for a work means the preferred form of the work for -making modifications to it. For an executable work, complete source -code means all the source code for all modules it contains, plus any -associated interface definition files, plus the scripts used to -control compilation and installation of the executable. However, as a -special exception, the source code distributed need not include -anything that is normally distributed (in either source or binary -form) with the major components (compiler, kernel, and so on) of the -operating system on which the executable runs, unless that component -itself accompanies the executable. - -If distribution of executable or object code is made by offering -access to copy from a designated place, then offering equivalent -access to copy the source code from the same place counts as -distribution of the source code, even though third parties are not -compelled to copy the source along with the object code. - - 4. You may not copy, modify, sublicense, or distribute the Program -except as expressly provided under this License. Any attempt -otherwise to copy, modify, sublicense or distribute the Program is -void, and will automatically terminate your rights under this License. -However, parties who have received copies, or rights, from you under -this License will not have their licenses terminated so long as such -parties remain in full compliance. - - 5. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Program or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Program (or any work based on the -Program), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Program or works based on it. - - 6. Each time you redistribute the Program (or any work based on the -Program), the recipient automatically receives a license from the -original licensor to copy, distribute or modify the Program subject to -these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties to -this License. - - 7. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Program at all. For example, if a patent -license would not permit royalty-free redistribution of the Program by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Program. - -If any portion of this section is held invalid or unenforceable under -any particular circumstance, the balance of the section is intended to -apply and the section as a whole is intended to apply in other -circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system, which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 8. If the distribution and/or use of the Program is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Program under this License -may add an explicit geographical distribution limitation excluding -those countries, so that distribution is permitted only in or among -countries not thus excluded. In such case, this License incorporates -the limitation as if written in the body of this License. - - 9. The Free Software Foundation may publish revised and/or new versions -of the General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - -Each version is given a distinguishing version number. If the Program -specifies a version number of this License which applies to it and "any -later version", you have the option of following the terms and conditions -either of that version or of any later version published by the Free -Software Foundation. If the Program does not specify a version number of -this License, you may choose any version ever published by the Free Software -Foundation. - - 10. If you wish to incorporate parts of the Program into other free -programs whose distribution conditions are different, write to the author -to ask for permission. For software which is copyrighted by the Free -Software Foundation, write to the Free Software Foundation; we sometimes -make exceptions for this. Our decision will be guided by the two goals -of preserving the free status of all derivatives of our free software and -of promoting the sharing and reuse of software generally. - - NO WARRANTY - - 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY -FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN -OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES -PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED -OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS -TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE -PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, -REPAIR OR CORRECTION. - - 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR -REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, -INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING -OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED -TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY -YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER -PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE -POSSIBILITY OF SUCH DAMAGES. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -convey the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License along - with this program; if not, write to the Free Software Foundation, Inc., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - -Also add information on how to contact you by electronic and paper mail. - -If the program is interactive, make it output a short notice like this -when it starts in an interactive mode: - - Gnomovision version 69, Copyright (C) year name of author - Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, the commands you use may -be called something other than `show w' and `show c'; they could even be -mouse-clicks or menu items--whatever suits your program. - -You should also get your employer (if you work as a programmer) or your -school, if any, to sign a "copyright disclaimer" for the program, if -necessary. Here is a sample; alter the names: - - Yoyodyne, Inc., hereby disclaims all copyright interest in the program - `Gnomovision' (which makes passes at compilers) written by James Hacker. - - , 1 April 1989 - Ty Coon, President of Vice - -This General Public License does not permit incorporating your program into -proprietary programs. If your program is a subroutine library, you may -consider it more useful to permit linking proprietary applications with the -library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid-2.4.2.dist-info/COPYING.LESSER b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid-2.4.2.dist-info/COPYING.LESSER deleted file mode 100644 index 2d2d780..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid-2.4.2.dist-info/COPYING.LESSER +++ /dev/null @@ -1,510 +0,0 @@ - - GNU LESSER GENERAL PUBLIC LICENSE - Version 2.1, February 1999 - - Copyright (C) 1991, 1999 Free Software Foundation, Inc. - 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - -[This is the first released version of the Lesser GPL. It also counts - as the successor of the GNU Library Public License, version 2, hence - the version number 2.1.] - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -Licenses are intended to guarantee your freedom to share and change -free software--to make sure the software is free for all its users. - - This license, the Lesser General Public License, applies to some -specially designated software packages--typically libraries--of the -Free Software Foundation and other authors who decide to use it. You -can use it too, but we suggest you first think carefully about whether -this license or the ordinary General Public License is the better -strategy to use in any particular case, based on the explanations -below. - - When we speak of free software, we are referring to freedom of use, -not price. Our General Public Licenses are designed to make sure that -you have the freedom to distribute copies of free software (and charge -for this service if you wish); that you receive source code or can get -it if you want it; that you can change the software and use pieces of -it in new free programs; and that you are informed that you can do -these things. - - To protect your rights, we need to make restrictions that forbid -distributors to deny you these rights or to ask you to surrender these -rights. These restrictions translate to certain responsibilities for -you if you distribute copies of the library or if you modify it. - - For example, if you distribute copies of the library, whether gratis -or for a fee, you must give the recipients all the rights that we gave -you. You must make sure that they, too, receive or can get the source -code. If you link other code with the library, you must provide -complete object files to the recipients, so that they can relink them -with the library after making changes to the library and recompiling -it. And you must show them these terms so they know their rights. - - We protect your rights with a two-step method: (1) we copyright the -library, and (2) we offer you this license, which gives you legal -permission to copy, distribute and/or modify the library. - - To protect each distributor, we want to make it very clear that -there is no warranty for the free library. Also, if the library is -modified by someone else and passed on, the recipients should know -that what they have is not the original version, so that the original -author's reputation will not be affected by problems that might be -introduced by others. - - Finally, software patents pose a constant threat to the existence of -any free program. We wish to make sure that a company cannot -effectively restrict the users of a free program by obtaining a -restrictive license from a patent holder. Therefore, we insist that -any patent license obtained for a version of the library must be -consistent with the full freedom of use specified in this license. - - Most GNU software, including some libraries, is covered by the -ordinary GNU General Public License. This license, the GNU Lesser -General Public License, applies to certain designated libraries, and -is quite different from the ordinary General Public License. We use -this license for certain libraries in order to permit linking those -libraries into non-free programs. - - When a program is linked with a library, whether statically or using -a shared library, the combination of the two is legally speaking a -combined work, a derivative of the original library. The ordinary -General Public License therefore permits such linking only if the -entire combination fits its criteria of freedom. The Lesser General -Public License permits more lax criteria for linking other code with -the library. - - We call this license the "Lesser" General Public License because it -does Less to protect the user's freedom than the ordinary General -Public License. It also provides other free software developers Less -of an advantage over competing non-free programs. These disadvantages -are the reason we use the ordinary General Public License for many -libraries. However, the Lesser license provides advantages in certain -special circumstances. - - For example, on rare occasions, there may be a special need to -encourage the widest possible use of a certain library, so that it -becomes a de-facto standard. To achieve this, non-free programs must -be allowed to use the library. A more frequent case is that a free -library does the same job as widely used non-free libraries. In this -case, there is little to gain by limiting the free library to free -software only, so we use the Lesser General Public License. - - In other cases, permission to use a particular library in non-free -programs enables a greater number of people to use a large body of -free software. For example, permission to use the GNU C Library in -non-free programs enables many more people to use the whole GNU -operating system, as well as its variant, the GNU/Linux operating -system. - - Although the Lesser General Public License is Less protective of the -users' freedom, it does ensure that the user of a program that is -linked with the Library has the freedom and the wherewithal to run -that program using a modified version of the Library. - - The precise terms and conditions for copying, distribution and -modification follow. Pay close attention to the difference between a -"work based on the library" and a "work that uses the library". The -former contains code derived from the library, whereas the latter must -be combined with the library in order to run. - - GNU LESSER GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License Agreement applies to any software library or other -program which contains a notice placed by the copyright holder or -other authorized party saying it may be distributed under the terms of -this Lesser General Public License (also called "this License"). -Each licensee is addressed as "you". - - A "library" means a collection of software functions and/or data -prepared so as to be conveniently linked with application programs -(which use some of those functions and data) to form executables. - - The "Library", below, refers to any such software library or work -which has been distributed under these terms. A "work based on the -Library" means either the Library or any derivative work under -copyright law: that is to say, a work containing the Library or a -portion of it, either verbatim or with modifications and/or translated -straightforwardly into another language. (Hereinafter, translation is -included without limitation in the term "modification".) - - "Source code" for a work means the preferred form of the work for -making modifications to it. For a library, complete source code means -all the source code for all modules it contains, plus any associated -interface definition files, plus the scripts used to control -compilation and installation of the library. - - Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running a program using the Library is not restricted, and output from -such a program is covered only if its contents constitute a work based -on the Library (independent of the use of the Library in a tool for -writing it). Whether that is true depends on what the Library does -and what the program that uses the Library does. - - 1. You may copy and distribute verbatim copies of the Library's -complete source code as you receive it, in any medium, provided that -you conspicuously and appropriately publish on each copy an -appropriate copyright notice and disclaimer of warranty; keep intact -all the notices that refer to this License and to the absence of any -warranty; and distribute a copy of this License along with the -Library. - - You may charge a fee for the physical act of transferring a copy, -and you may at your option offer warranty protection in exchange for a -fee. - - 2. You may modify your copy or copies of the Library or any portion -of it, thus forming a work based on the Library, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) The modified work must itself be a software library. - - b) You must cause the files modified to carry prominent notices - stating that you changed the files and the date of any change. - - c) You must cause the whole of the work to be licensed at no - charge to all third parties under the terms of this License. - - d) If a facility in the modified Library refers to a function or a - table of data to be supplied by an application program that uses - the facility, other than as an argument passed when the facility - is invoked, then you must make a good faith effort to ensure that, - in the event an application does not supply such function or - table, the facility still operates, and performs whatever part of - its purpose remains meaningful. - - (For example, a function in a library to compute square roots has - a purpose that is entirely well-defined independent of the - application. Therefore, Subsection 2d requires that any - application-supplied function or table used by this function must - be optional: if the application does not supply it, the square - root function must still compute square roots.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Library, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Library, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote -it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Library. - -In addition, mere aggregation of another work not based on the Library -with the Library (or with a work based on the Library) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may opt to apply the terms of the ordinary GNU General Public -License instead of this License to a given copy of the Library. To do -this, you must alter all the notices that refer to this License, so -that they refer to the ordinary GNU General Public License, version 2, -instead of to this License. (If a newer version than version 2 of the -ordinary GNU General Public License has appeared, then you can specify -that version instead if you wish.) Do not make any other change in -these notices. - - Once this change is made in a given copy, it is irreversible for -that copy, so the ordinary GNU General Public License applies to all -subsequent copies and derivative works made from that copy. - - This option is useful when you wish to copy part of the code of -the Library into a program that is not a library. - - 4. You may copy and distribute the Library (or a portion or -derivative of it, under Section 2) in object code or executable form -under the terms of Sections 1 and 2 above provided that you accompany -it with the complete corresponding machine-readable source code, which -must be distributed under the terms of Sections 1 and 2 above on a -medium customarily used for software interchange. - - If distribution of object code is made by offering access to copy -from a designated place, then offering equivalent access to copy the -source code from the same place satisfies the requirement to -distribute the source code, even though third parties are not -compelled to copy the source along with the object code. - - 5. A program that contains no derivative of any portion of the -Library, but is designed to work with the Library by being compiled or -linked with it, is called a "work that uses the Library". Such a -work, in isolation, is not a derivative work of the Library, and -therefore falls outside the scope of this License. - - However, linking a "work that uses the Library" with the Library -creates an executable that is a derivative of the Library (because it -contains portions of the Library), rather than a "work that uses the -library". The executable is therefore covered by this License. -Section 6 states terms for distribution of such executables. - - When a "work that uses the Library" uses material from a header file -that is part of the Library, the object code for the work may be a -derivative work of the Library even though the source code is not. -Whether this is true is especially significant if the work can be -linked without the Library, or if the work is itself a library. The -threshold for this to be true is not precisely defined by law. - - If such an object file uses only numerical parameters, data -structure layouts and accessors, and small macros and small inline -functions (ten lines or less in length), then the use of the object -file is unrestricted, regardless of whether it is legally a derivative -work. (Executables containing this object code plus portions of the -Library will still fall under Section 6.) - - Otherwise, if the work is a derivative of the Library, you may -distribute the object code for the work under the terms of Section 6. -Any executables containing that work also fall under Section 6, -whether or not they are linked directly with the Library itself. - - 6. As an exception to the Sections above, you may also combine or -link a "work that uses the Library" with the Library to produce a -work containing portions of the Library, and distribute that work -under terms of your choice, provided that the terms permit -modification of the work for the customer's own use and reverse -engineering for debugging such modifications. - - You must give prominent notice with each copy of the work that the -Library is used in it and that the Library and its use are covered by -this License. You must supply a copy of this License. If the work -during execution displays copyright notices, you must include the -copyright notice for the Library among them, as well as a reference -directing the user to the copy of this License. Also, you must do one -of these things: - - a) Accompany the work with the complete corresponding - machine-readable source code for the Library including whatever - changes were used in the work (which must be distributed under - Sections 1 and 2 above); and, if the work is an executable linked - with the Library, with the complete machine-readable "work that - uses the Library", as object code and/or source code, so that the - user can modify the Library and then relink to produce a modified - executable containing the modified Library. (It is understood - that the user who changes the contents of definitions files in the - Library will not necessarily be able to recompile the application - to use the modified definitions.) - - b) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (1) uses at run time a - copy of the library already present on the user's computer system, - rather than copying library functions into the executable, and (2) - will operate properly with a modified version of the library, if - the user installs one, as long as the modified version is - interface-compatible with the version that the work was made with. - - c) Accompany the work with a written offer, valid for at least - three years, to give the same user the materials specified in - Subsection 6a, above, for a charge no more than the cost of - performing this distribution. - - d) If distribution of the work is made by offering access to copy - from a designated place, offer equivalent access to copy the above - specified materials from the same place. - - e) Verify that the user has already received a copy of these - materials or that you have already sent this user a copy. - - For an executable, the required form of the "work that uses the -Library" must include any data and utility programs needed for -reproducing the executable from it. However, as a special exception, -the materials to be distributed need not include anything that is -normally distributed (in either source or binary form) with the major -components (compiler, kernel, and so on) of the operating system on -which the executable runs, unless that component itself accompanies -the executable. - - It may happen that this requirement contradicts the license -restrictions of other proprietary libraries that do not normally -accompany the operating system. Such a contradiction means you cannot -use both them and the Library together in an executable that you -distribute. - - 7. You may place library facilities that are a work based on the -Library side-by-side in a single library together with other library -facilities not covered by this License, and distribute such a combined -library, provided that the separate distribution of the work based on -the Library and of the other library facilities is otherwise -permitted, and provided that you do these two things: - - a) Accompany the combined library with a copy of the same work - based on the Library, uncombined with any other library - facilities. This must be distributed under the terms of the - Sections above. - - b) Give prominent notice with the combined library of the fact - that part of it is a work based on the Library, and explaining - where to find the accompanying uncombined form of the same work. - - 8. You may not copy, modify, sublicense, link with, or distribute -the Library except as expressly provided under this License. Any -attempt otherwise to copy, modify, sublicense, link with, or -distribute the Library is void, and will automatically terminate your -rights under this License. However, parties who have received copies, -or rights, from you under this License will not have their licenses -terminated so long as such parties remain in full compliance. - - 9. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Library or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Library (or any work based on the -Library), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Library or works based on it. - - 10. Each time you redistribute the Library (or any work based on the -Library), the recipient automatically receives a license from the -original licensor to copy, distribute, link with or modify the Library -subject to these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties with -this License. - - 11. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Library at all. For example, if a patent -license would not permit royalty-free redistribution of the Library by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Library. - -If any portion of this section is held invalid or unenforceable under -any particular circumstance, the balance of the section is intended to -apply, and the section as a whole is intended to apply in other -circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 12. If the distribution and/or use of the Library is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Library under this License -may add an explicit geographical distribution limitation excluding those -countries, so that distribution is permitted only in or among -countries not thus excluded. In such case, this License incorporates -the limitation as if written in the body of this License. - - 13. The Free Software Foundation may publish revised and/or new -versions of the Lesser General Public License from time to time. -Such new versions will be similar in spirit to the present version, -but may differ in detail to address new problems or concerns. - -Each version is given a distinguishing version number. If the Library -specifies a version number of this License which applies to it and -"any later version", you have the option of following the terms and -conditions either of that version or of any later version published by -the Free Software Foundation. If the Library does not specify a -license version number, you may choose any version ever published by -the Free Software Foundation. - - 14. If you wish to incorporate parts of the Library into other free -programs whose distribution conditions are incompatible with these, -write to the author to ask for permission. For software which is -copyrighted by the Free Software Foundation, write to the Free -Software Foundation; we sometimes make exceptions for this. Our -decision will be guided by the two goals of preserving the free status -of all derivatives of our free software and of promoting the sharing -and reuse of software generally. - - NO WARRANTY - - 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO -WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. -EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR -OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY -KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE -LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME -THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN -WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY -AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU -FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR -CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE -LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING -RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A -FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF -SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH -DAMAGES. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Libraries - - If you develop a new library, and you want it to be of the greatest -possible use to the public, we recommend making it free software that -everyone can redistribute and change. You can do so by permitting -redistribution under these terms (or, alternatively, under the terms -of the ordinary General Public License). - - To apply these terms, attach the following notices to the library. -It is safest to attach them to the start of each source file to most -effectively convey the exclusion of warranty; and each file should -have at least the "copyright" line and a pointer to where the full -notice is found. - - - - Copyright (C) - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - -Also add information on how to contact you by electronic and paper mail. - -You should also get your employer (if you work as a programmer) or -your school, if any, to sign a "copyright disclaimer" for the library, -if necessary. Here is a sample; alter the names: - - Yoyodyne, Inc., hereby disclaims all copyright interest in the - library `Frob' (a library for tweaking knobs) written by James - Random Hacker. - - , 1 April 1990 - Ty Coon, President of Vice - -That's all there is to it! - - diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid-2.4.2.dist-info/INSTALLER b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid-2.4.2.dist-info/INSTALLER deleted file mode 100644 index a1b589e..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid-2.4.2.dist-info/INSTALLER +++ /dev/null @@ -1 +0,0 @@ -pip diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid-2.4.2.dist-info/METADATA b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid-2.4.2.dist-info/METADATA deleted file mode 100644 index 47dad94..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid-2.4.2.dist-info/METADATA +++ /dev/null @@ -1,118 +0,0 @@ -Metadata-Version: 2.1 -Name: astroid -Version: 2.4.2 -Summary: An abstract syntax tree for Python with inference support. -Home-page: https://github.com/PyCQA/astroid -Author: Python Code Quality Authority -Author-email: code-quality@python.org -License: LGPL -Platform: UNKNOWN -Classifier: Topic :: Software Development :: Libraries :: Python Modules -Classifier: Topic :: Software Development :: Quality Assurance -Classifier: Programming Language :: Python -Classifier: Programming Language :: Python :: 3 -Classifier: Programming Language :: Python :: 3.5 -Classifier: Programming Language :: Python :: 3.6 -Classifier: Programming Language :: Python :: 3.7 -Classifier: Programming Language :: Python :: 3.8 -Classifier: Programming Language :: Python :: Implementation :: CPython -Classifier: Programming Language :: Python :: Implementation :: PyPy -Requires-Python: >=3.5 -Requires-Dist: lazy-object-proxy (==1.4.*) -Requires-Dist: six (~=1.12) -Requires-Dist: wrapt (~=1.11) -Requires-Dist: typed-ast (<1.5,>=1.4.0) ; implementation_name == "cpython" and python_version < "3.8" - -Astroid -======= - -.. image:: https://travis-ci.org/PyCQA/astroid.svg?branch=master - :target: https://travis-ci.org/PyCQA/astroid - -.. image:: https://ci.appveyor.com/api/projects/status/co3u42kunguhbh6l/branch/master?svg=true - :alt: AppVeyor Build Status - :target: https://ci.appveyor.com/project/PCManticore/astroid - -.. image:: https://coveralls.io/repos/github/PyCQA/astroid/badge.svg?branch=master - :target: https://coveralls.io/github/PyCQA/astroid?branch=master - -.. image:: https://readthedocs.org/projects/astroid/badge/?version=latest - :target: http://astroid.readthedocs.io/en/latest/?badge=latest - :alt: Documentation Status - -.. image:: https://img.shields.io/badge/code%20style-black-000000.svg - :target: https://github.com/ambv/black - -.. |tideliftlogo| image:: doc/media/Tidelift_Logos_RGB_Tidelift_Shorthand_On-White_small.png - :width: 75 - :height: 60 - :alt: Tidelift - -.. list-table:: - :widths: 10 100 - - * - |tideliftlogo| - - Professional support for astroid is available as part of the `Tidelift - Subscription`_. Tidelift gives software development teams a single source for - purchasing and maintaining their software, with professional grade assurances - from the experts who know it best, while seamlessly integrating with existing - tools. - -.. _Tidelift Subscription: https://tidelift.com/subscription/pkg/pypi-astroid?utm_source=pypi-astroid&utm_medium=referral&utm_campaign=readme - - - -What's this? ------------- - -The aim of this module is to provide a common base representation of -python source code. It is currently the library powering pylint's capabilities. - -It provides a compatible representation which comes from the `_ast` -module. It rebuilds the tree generated by the builtin _ast module by -recursively walking down the AST and building an extended ast. The new -node classes have additional methods and attributes for different -usages. They include some support for static inference and local name -scopes. Furthermore, astroid can also build partial trees by inspecting living -objects. - - -Installation ------------- - -Extract the tarball, jump into the created directory and run:: - - pip install . - - -If you want to do an editable installation, you can run:: - - pip install -e . - - -If you have any questions, please mail the code-quality@python.org -mailing list for support. See -http://mail.python.org/mailman/listinfo/code-quality for subscription -information and archives. - -Documentation -------------- -http://astroid.readthedocs.io/en/latest/ - - -Python Versions ---------------- - -astroid 2.0 is currently available for Python 3 only. If you want Python 2 -support, older versions of astroid will still supported until 2020. - -Test ----- - -Tests are in the 'test' subdirectory. To launch the whole tests suite, you can use -either `tox` or `pytest`:: - - tox - pytest astroid - - diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid-2.4.2.dist-info/RECORD b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid-2.4.2.dist-info/RECORD deleted file mode 100644 index feed06a..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid-2.4.2.dist-info/RECORD +++ /dev/null @@ -1,151 +0,0 @@ -astroid-2.4.2.dist-info/COPYING,sha256=qxX9UmvY3Rip5368E5ZWv00z6X_HI4zRG_YOK5uGZsY,17987 -astroid-2.4.2.dist-info/COPYING.LESSER,sha256=qb3eVhbs3R6YC0TzYGAO6Hg7H5m4zIOivrFjoKOQ6GE,26527 -astroid-2.4.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 -astroid-2.4.2.dist-info/METADATA,sha256=mWlOM8vl6thD_vA7Lzn2yKmQuaX8NukwS72gEpsGM0U,3915 -astroid-2.4.2.dist-info/RECORD,, -astroid-2.4.2.dist-info/WHEEL,sha256=g4nMs7d-Xl9-xC9XovUrsDHGXt-FT0E17Yqo92DEfvY,92 -astroid-2.4.2.dist-info/top_level.txt,sha256=HsdW4O2x7ZXRj6k-agi3RaQybGLobI3VSE-jt4vQUXM,8 -astroid/__init__.py,sha256=zZF5EWBTfOtOcFd62WMbhLAtS2b_Fm-3JJW2AVUUMUI,5655 -astroid/__pkginfo__.py,sha256=G6QlkatrWucF445cQW7Kb2ZSgBzf7TiKLPwqkP0CoQU,2329 -astroid/__pycache__/__init__.cpython-38.pyc,, -astroid/__pycache__/__pkginfo__.cpython-38.pyc,, -astroid/__pycache__/_ast.cpython-38.pyc,, -astroid/__pycache__/arguments.cpython-38.pyc,, -astroid/__pycache__/as_string.cpython-38.pyc,, -astroid/__pycache__/bases.cpython-38.pyc,, -astroid/__pycache__/builder.cpython-38.pyc,, -astroid/__pycache__/context.cpython-38.pyc,, -astroid/__pycache__/decorators.cpython-38.pyc,, -astroid/__pycache__/exceptions.cpython-38.pyc,, -astroid/__pycache__/helpers.cpython-38.pyc,, -astroid/__pycache__/inference.cpython-38.pyc,, -astroid/__pycache__/manager.cpython-38.pyc,, -astroid/__pycache__/mixins.cpython-38.pyc,, -astroid/__pycache__/modutils.cpython-38.pyc,, -astroid/__pycache__/node_classes.cpython-38.pyc,, -astroid/__pycache__/nodes.cpython-38.pyc,, -astroid/__pycache__/objects.cpython-38.pyc,, -astroid/__pycache__/protocols.cpython-38.pyc,, -astroid/__pycache__/raw_building.cpython-38.pyc,, -astroid/__pycache__/rebuilder.cpython-38.pyc,, -astroid/__pycache__/scoped_nodes.cpython-38.pyc,, -astroid/__pycache__/test_utils.cpython-38.pyc,, -astroid/__pycache__/transforms.cpython-38.pyc,, -astroid/__pycache__/util.cpython-38.pyc,, -astroid/_ast.py,sha256=n1U2HblBNrMhsmrjF84HUfIgEZ3PyHyiJJOrOkgiUFk,3385 -astroid/arguments.py,sha256=KJcZn7HeEhj2fZICr-9Pi7iueCNDZRQWh0T7O-qb-AE,12558 -astroid/as_string.py,sha256=8bOZWsGG79TLmlzRzPtmHdanIAqQUFTKiYH873iMhOw,22821 -astroid/bases.py,sha256=wL9C23mHFaj7vhMqM83DdsU6kfP488aEjoFWaO8p6Cg,19175 -astroid/brain/__pycache__/brain_argparse.cpython-38.pyc,, -astroid/brain/__pycache__/brain_attrs.cpython-38.pyc,, -astroid/brain/__pycache__/brain_boto3.cpython-38.pyc,, -astroid/brain/__pycache__/brain_builtin_inference.cpython-38.pyc,, -astroid/brain/__pycache__/brain_collections.cpython-38.pyc,, -astroid/brain/__pycache__/brain_crypt.cpython-38.pyc,, -astroid/brain/__pycache__/brain_curses.cpython-38.pyc,, -astroid/brain/__pycache__/brain_dataclasses.cpython-38.pyc,, -astroid/brain/__pycache__/brain_dateutil.cpython-38.pyc,, -astroid/brain/__pycache__/brain_fstrings.cpython-38.pyc,, -astroid/brain/__pycache__/brain_functools.cpython-38.pyc,, -astroid/brain/__pycache__/brain_gi.cpython-38.pyc,, -astroid/brain/__pycache__/brain_hashlib.cpython-38.pyc,, -astroid/brain/__pycache__/brain_http.cpython-38.pyc,, -astroid/brain/__pycache__/brain_io.cpython-38.pyc,, -astroid/brain/__pycache__/brain_mechanize.cpython-38.pyc,, -astroid/brain/__pycache__/brain_multiprocessing.cpython-38.pyc,, -astroid/brain/__pycache__/brain_namedtuple_enum.cpython-38.pyc,, -astroid/brain/__pycache__/brain_nose.cpython-38.pyc,, -astroid/brain/__pycache__/brain_numpy_core_fromnumeric.cpython-38.pyc,, -astroid/brain/__pycache__/brain_numpy_core_function_base.cpython-38.pyc,, -astroid/brain/__pycache__/brain_numpy_core_multiarray.cpython-38.pyc,, -astroid/brain/__pycache__/brain_numpy_core_numeric.cpython-38.pyc,, -astroid/brain/__pycache__/brain_numpy_core_numerictypes.cpython-38.pyc,, -astroid/brain/__pycache__/brain_numpy_core_umath.cpython-38.pyc,, -astroid/brain/__pycache__/brain_numpy_ndarray.cpython-38.pyc,, -astroid/brain/__pycache__/brain_numpy_random_mtrand.cpython-38.pyc,, -astroid/brain/__pycache__/brain_numpy_utils.cpython-38.pyc,, -astroid/brain/__pycache__/brain_pkg_resources.cpython-38.pyc,, -astroid/brain/__pycache__/brain_pytest.cpython-38.pyc,, -astroid/brain/__pycache__/brain_qt.cpython-38.pyc,, -astroid/brain/__pycache__/brain_random.cpython-38.pyc,, -astroid/brain/__pycache__/brain_re.cpython-38.pyc,, -astroid/brain/__pycache__/brain_responses.cpython-38.pyc,, -astroid/brain/__pycache__/brain_scipy_signal.cpython-38.pyc,, -astroid/brain/__pycache__/brain_six.cpython-38.pyc,, -astroid/brain/__pycache__/brain_ssl.cpython-38.pyc,, -astroid/brain/__pycache__/brain_subprocess.cpython-38.pyc,, -astroid/brain/__pycache__/brain_threading.cpython-38.pyc,, -astroid/brain/__pycache__/brain_typing.cpython-38.pyc,, -astroid/brain/__pycache__/brain_uuid.cpython-38.pyc,, -astroid/brain/brain_argparse.py,sha256=5XqcThekktCIWRlWAMs-R47wkbsOUSnQlsEbLEnRpsY,1041 -astroid/brain/brain_attrs.py,sha256=k8zJqIXsIbQrncthrzyB5NtdPTktgVi9wG7nyl8xMzs,2208 -astroid/brain/brain_boto3.py,sha256=nE8Cw_S_Gp___IszRDRkhEGS6WGrKcF_gTOs3GVxH9k,862 -astroid/brain/brain_builtin_inference.py,sha256=F6_09yM2mmu_u3ad_f9Uumc-q0lDA2CY8v9-PYtUMmA,28793 -astroid/brain/brain_collections.py,sha256=Uqi4VmpLDl0ndQa9x-5tIXRtVdtI6TlwR9KNHmOqLyw,2724 -astroid/brain/brain_crypt.py,sha256=gA7Q4GVuAM4viuTGWM6SNTPQXv5Gr_mFapyKMTRcsJ0,875 -astroid/brain/brain_curses.py,sha256=tDnlCP1bEvleqCMz856yua9mM5um1p_JendFhT4rBFk,3303 -astroid/brain/brain_dataclasses.py,sha256=5WndOYSY0oi2v-Od6KdPte-FKt00LoNRH2riSB4S1os,1647 -astroid/brain/brain_dateutil.py,sha256=GwDrgbaUkKbp3ImLAvuUtPuDBeK3lPh0bNI_Wphm2_8,801 -astroid/brain/brain_fstrings.py,sha256=Jaf-G-wkLecwG4jfjjfR8MDKzgAjjn2mgrrWZQLOAd8,2126 -astroid/brain/brain_functools.py,sha256=Nljy7o2vu16S2amFot4wdTI0U76Yafq-ujVPHOdGgCE,5481 -astroid/brain/brain_gi.py,sha256=oraXhBWyCCxmPEAEvRboeTIho0--ORObvckni00_1wY,7554 -astroid/brain/brain_hashlib.py,sha256=W2cS6-rixdBcre6lPWIuSOqPLCcVji5JBlImdPbV6Qo,2292 -astroid/brain/brain_http.py,sha256=a_8eIACvZetnR2xI4ZARVMuB1WSjyyqM3rCl2DVltMo,10524 -astroid/brain/brain_io.py,sha256=wEY3vvTeV23tYxFn8HHQeyjhb7-jqzwgwNI-kl2Yu-c,1476 -astroid/brain/brain_mechanize.py,sha256=boZxoCxPGSpHC_RccO5U026hyXyhunXR55M9WM1lYTo,895 -astroid/brain/brain_multiprocessing.py,sha256=9OswtRuVBj-KemJ0yp4prz8mrkJDzOzN6n13u2MgmwM,3096 -astroid/brain/brain_namedtuple_enum.py,sha256=eZ8IaHPLLHBakywJ3q4Ogtd2Tk0gtNcAgYAloMAKTjM,15966 -astroid/brain/brain_nose.py,sha256=PSPmme611h7fC8MKuVXbiGw0HZhdmIuoxM6yieZ1OOc,2217 -astroid/brain/brain_numpy_core_fromnumeric.py,sha256=NxiHbcMyQQ3Gpx4KEA5eAmGrpjlPN5rfXjRLjHPOVkw,621 -astroid/brain/brain_numpy_core_function_base.py,sha256=7i6Kge_PviqoWXhbeRgB581xwLo0dxvO54_5UB3ppig,1168 -astroid/brain/brain_numpy_core_multiarray.py,sha256=vr-nBt3EF_z-UmHmcAlJhGorgDXPpQaYX8g4TWu_2Vw,4015 -astroid/brain/brain_numpy_core_numeric.py,sha256=M0RXOym2YC-DaZfRqGNIpr6s-Oh1KHn1okGr3PtPl0k,1384 -astroid/brain/brain_numpy_core_numerictypes.py,sha256=ltlZyQprEbVdUJpC_ERGyXyJsYwzFHx7zGYDLheIonA,8013 -astroid/brain/brain_numpy_core_umath.py,sha256=je6K3ILMen2mgkZseHCOjOgnFV6SaNgAihEi6irhbRk,4436 -astroid/brain/brain_numpy_ndarray.py,sha256=WZbRG7GgOWZ68sEr4JjZUnJHLfUc91xp2mucHeLMrnw,8463 -astroid/brain/brain_numpy_random_mtrand.py,sha256=WRy_CStllgZN2B3Dw2qxXbY4SBrCzu-cdaK230VQHaE,3278 -astroid/brain/brain_numpy_utils.py,sha256=ZYtCVmn1x6P7iwYFohdW3CCrvVT5BCNYe-7jKcz_25s,1875 -astroid/brain/brain_pkg_resources.py,sha256=S_5UED1Zg8ObEJumRdpYGnjxZzemh_G_NFj3p5NGPfc,2262 -astroid/brain/brain_pytest.py,sha256=RYp7StKnC22n4vFJkHH5h7DAFWtouIcg-ZCXQ8Oz3xk,2390 -astroid/brain/brain_qt.py,sha256=m2s4YXFrnOynWDf9omHOBLVqFriBdGJAmvarJCxiffM,2536 -astroid/brain/brain_random.py,sha256=2RZY-QEXMNWp7E6h0l0-ke-DtjKTOFlTdjiQZi3XdQc,2432 -astroid/brain/brain_re.py,sha256=le7VJHUAf80HyE_aQCh7_8FyDVK6JwNWA--c9RaMVQ8,1128 -astroid/brain/brain_responses.py,sha256=GIAGkwMEGEZ9bJHI9uBGs_UmUy3DRBtjI_j_8dLBVsc,1534 -astroid/brain/brain_scipy_signal.py,sha256=IKNnGXzEH5FKhPHM2hv57pNdo1emThWwZ0ksckdsOeE,2255 -astroid/brain/brain_six.py,sha256=79aws4au6ZQJuf-YhBT4R-9wuVOwg-u0T42aUhCswK0,6187 -astroid/brain/brain_ssl.py,sha256=9dMCTQ0JsX2gpdmBkYO7BByw3zN23oXRL8Svo2S1V28,3722 -astroid/brain/brain_subprocess.py,sha256=yp-HsE69uh7T7C1kZYciAdRMQ48aNT51lI032oDppDk,4688 -astroid/brain/brain_threading.py,sha256=dY8YwZ-zrB30_CQFYWh4AK3qUVssakgwLVwunQ6yYkU,837 -astroid/brain/brain_typing.py,sha256=iFw33beNCitCJjJNvccIY6SsFJcdKVDdl-56DxDioh0,2780 -astroid/brain/brain_uuid.py,sha256=YzfiOXavu515cS1prsKGfY4-12g_KWT0Yr4-5ti0v74,569 -astroid/builder.py,sha256=72JlHrXRF9sS5zh1mqXlRHGFg88Efc2rm9yRJKDIShA,16891 -astroid/context.py,sha256=MpwiEzWZ39a4WyqYgbSmePL2nZLqALt1gjrvi3TP35U,5169 -astroid/decorators.py,sha256=z_wTjsiMlu_ElHtYUUuxaB2F_s4G0Ks7bmtCZS3IQ_Q,4283 -astroid/exceptions.py,sha256=GLiZo9BdWILJShO-il8ra-tPZqaODMAX987F--LWv2w,6891 -astroid/helpers.py,sha256=3YoJeVLoS-66T_abDorUNHiP8m2R7-faNnpc5yPJhrc,9448 -astroid/inference.py,sha256=UiKKPRYqb5JINQIw1lSdBniHhXjCohCGAqycp2GkVI4,34686 -astroid/interpreter/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 -astroid/interpreter/__pycache__/__init__.cpython-38.pyc,, -astroid/interpreter/__pycache__/dunder_lookup.cpython-38.pyc,, -astroid/interpreter/__pycache__/objectmodel.cpython-38.pyc,, -astroid/interpreter/_import/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 -astroid/interpreter/_import/__pycache__/__init__.cpython-38.pyc,, -astroid/interpreter/_import/__pycache__/spec.cpython-38.pyc,, -astroid/interpreter/_import/__pycache__/util.cpython-38.pyc,, -astroid/interpreter/_import/spec.py,sha256=rZ9kX3I0xPo_pFAYWeOk2Xbi4ZIg_5bRsouZgxOXegA,11436 -astroid/interpreter/_import/util.py,sha256=inubUz6F3_kaMFaeleKUW6E6wCMIPrhU882zvwEZ02I,255 -astroid/interpreter/dunder_lookup.py,sha256=dP-AZU_aGPNt03b1ttrMglxzeU3NtgnG0MfpSLPH6sg,2155 -astroid/interpreter/objectmodel.py,sha256=bbPIaamrqrx7WHtG5YNs9dbrlDC00GrJPxPGoSTsnqg,25792 -astroid/manager.py,sha256=jmEm9uH00mPA2Y68s10xrPNbZaadv_2c-CWluB3SYoE,13701 -astroid/mixins.py,sha256=F2rv2Ow7AU3YT_2jitVJik95ZWRVK6hpf8BrkkspzUY,5571 -astroid/modutils.py,sha256=GBW5Z691eqf6VAnPsZzeQ0WYzrl-0GGTHkkZNb_9XRQ,23242 -astroid/node_classes.py,sha256=cBRkZ_u8ZoRkiXznYWq1L3I7cO-P9nGowNCy8T7Qpzk,142740 -astroid/nodes.py,sha256=WoyRe22GNVRc2TRHWOUlqdxCdOVD8GKOq9v1LpPhkr8,2978 -astroid/objects.py,sha256=caKeQPBtrrfqa1q844vkehXwpdMzvph5YJdJJdbD_m8,11035 -astroid/protocols.py,sha256=m1ZHvKvFQZSZp993na4f9s8V17kqNPRfH-XpQc8gJ7c,27396 -astroid/raw_building.py,sha256=PI70y2mPQ7JURDVyNZ6deeBFkvjNNaOQBkuo0VPbvQ4,17340 -astroid/rebuilder.py,sha256=xn82eWlxzGcDd2VACUnNNWCxArfV9HI8g67fUip0XFk,39411 -astroid/scoped_nodes.py,sha256=fUrmTyltaLCr9-i8RdC2e5dPA9O8w946Mvvft8mgXdM,98203 -astroid/test_utils.py,sha256=axGB3j6ZEaVspL1ZgPizKgWehNEREb58Z97U7mQ-GA8,2319 -astroid/transforms.py,sha256=1npwJWcQUSIjcpcWd1pc-dJhtHOyiboQHsETAIQd5co,3377 -astroid/util.py,sha256=jg5LnqbWSZTZP1KgpxGBuC6Lfwhn9Jb2T2TohXghmC0,4785 diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid-2.4.2.dist-info/WHEEL b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid-2.4.2.dist-info/WHEEL deleted file mode 100644 index b552003..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid-2.4.2.dist-info/WHEEL +++ /dev/null @@ -1,5 +0,0 @@ -Wheel-Version: 1.0 -Generator: bdist_wheel (0.34.2) -Root-Is-Purelib: true -Tag: py3-none-any - diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid-2.4.2.dist-info/top_level.txt b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid-2.4.2.dist-info/top_level.txt deleted file mode 100644 index 450d4fe..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid-2.4.2.dist-info/top_level.txt +++ /dev/null @@ -1 +0,0 @@ -astroid diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__init__.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__init__.py deleted file mode 100644 index e869274..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__init__.py +++ /dev/null @@ -1,168 +0,0 @@ -# Copyright (c) 2006-2013, 2015 LOGILAB S.A. (Paris, FRANCE) -# Copyright (c) 2014 Google, Inc. -# Copyright (c) 2014 Eevee (Alex Munroe) -# Copyright (c) 2015-2016, 2018 Claudiu Popa -# Copyright (c) 2015-2016 Ceridwen -# Copyright (c) 2016 Derek Gustafson -# Copyright (c) 2016 Moises Lopez -# Copyright (c) 2018 Bryce Guinta -# Copyright (c) 2019 Nick Drozd - -# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html -# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER - -"""Python Abstract Syntax Tree New Generation - -The aim of this module is to provide a common base representation of -python source code for projects such as pychecker, pyreverse, -pylint... Well, actually the development of this library is essentially -governed by pylint's needs. - -It extends class defined in the python's _ast module with some -additional methods and attributes. Instance attributes are added by a -builder object, which can either generate extended ast (let's call -them astroid ;) by visiting an existent ast tree or by inspecting living -object. Methods are added by monkey patching ast classes. - -Main modules are: - -* nodes and scoped_nodes for more information about methods and - attributes added to different node classes - -* the manager contains a high level object to get astroid trees from - source files and living objects. It maintains a cache of previously - constructed tree for quick access - -* builder contains the class responsible to build astroid trees -""" - -import enum -import itertools -import os -import sys - -import wrapt - - -_Context = enum.Enum("Context", "Load Store Del") -Load = _Context.Load -Store = _Context.Store -Del = _Context.Del -del _Context - - -# pylint: disable=wrong-import-order,wrong-import-position -from .__pkginfo__ import version as __version__ - -# WARNING: internal imports order matters ! - -# pylint: disable=redefined-builtin - -# make all exception classes accessible from astroid package -from astroid.exceptions import * - -# make all node classes accessible from astroid package -from astroid.nodes import * - -# trigger extra monkey-patching -from astroid import inference - -# more stuff available -from astroid import raw_building -from astroid.bases import BaseInstance, Instance, BoundMethod, UnboundMethod -from astroid.node_classes import are_exclusive, unpack_infer -from astroid.scoped_nodes import builtin_lookup -from astroid.builder import parse, extract_node -from astroid.util import Uninferable - -# make a manager instance (borg) accessible from astroid package -from astroid.manager import AstroidManager - -MANAGER = AstroidManager() -del AstroidManager - -# transform utilities (filters and decorator) - - -# pylint: disable=dangerous-default-value -@wrapt.decorator -def _inference_tip_cached(func, instance, args, kwargs, _cache={}): - """Cache decorator used for inference tips""" - node = args[0] - try: - return iter(_cache[func, node]) - except KeyError: - result = func(*args, **kwargs) - # Need to keep an iterator around - original, copy = itertools.tee(result) - _cache[func, node] = list(copy) - return original - - -# pylint: enable=dangerous-default-value - - -def inference_tip(infer_function, raise_on_overwrite=False): - """Given an instance specific inference function, return a function to be - given to MANAGER.register_transform to set this inference function. - - :param bool raise_on_overwrite: Raise an `InferenceOverwriteError` - if the inference tip will overwrite another. Used for debugging - - Typical usage - - .. sourcecode:: python - - MANAGER.register_transform(Call, inference_tip(infer_named_tuple), - predicate) - - .. Note:: - - Using an inference tip will override - any previously set inference tip for the given - node. Use a predicate in the transform to prevent - excess overwrites. - """ - - def transform(node, infer_function=infer_function): - if ( - raise_on_overwrite - and node._explicit_inference is not None - and node._explicit_inference is not infer_function - ): - raise InferenceOverwriteError( - "Inference already set to {existing_inference}. " - "Trying to overwrite with {new_inference} for {node}".format( - existing_inference=infer_function, - new_inference=node._explicit_inference, - node=node, - ) - ) - # pylint: disable=no-value-for-parameter - node._explicit_inference = _inference_tip_cached(infer_function) - return node - - return transform - - -def register_module_extender(manager, module_name, get_extension_mod): - def transform(node): - extension_module = get_extension_mod() - for name, objs in extension_module.locals.items(): - node.locals[name] = objs - for obj in objs: - if obj.parent is extension_module: - obj.parent = node - - manager.register_transform(Module, transform, lambda n: n.name == module_name) - - -# load brain plugins -BRAIN_MODULES_DIR = os.path.join(os.path.dirname(__file__), "brain") -if BRAIN_MODULES_DIR not in sys.path: - # add it to the end of the list so user path take precedence - sys.path.append(BRAIN_MODULES_DIR) -# load modules in this directory -for module in os.listdir(BRAIN_MODULES_DIR): - if module.endswith(".py"): - __import__(module[:-3]) diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pkginfo__.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pkginfo__.py deleted file mode 100644 index fd8e132..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pkginfo__.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright (c) 2006-2014 LOGILAB S.A. (Paris, FRANCE) -# Copyright (c) 2014-2019 Claudiu Popa -# Copyright (c) 2014 Google, Inc. -# Copyright (c) 2015-2017 Ceridwen -# Copyright (c) 2015 Florian Bruhin -# Copyright (c) 2015 Radosław Ganczarek -# Copyright (c) 2016 Moises Lopez -# Copyright (c) 2017 Hugo -# Copyright (c) 2017 Łukasz Rogalski -# Copyright (c) 2017 Calen Pennington -# Copyright (c) 2018 Ville Skyttä -# Copyright (c) 2018 Ashley Whetter -# Copyright (c) 2018 Bryce Guinta -# Copyright (c) 2019 Uilian Ries -# Copyright (c) 2019 Thomas Hisch -# Copyright (c) 2020 Michael - -# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html -# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER - -"""astroid packaging information""" - -version = "2.4.2" -numversion = tuple(int(elem) for elem in version.split(".") if elem.isdigit()) - -extras_require = {} -install_requires = [ - "lazy_object_proxy==1.4.*", - "six~=1.12", - "wrapt~=1.11", - 'typed-ast>=1.4.0,<1.5;implementation_name== "cpython" and python_version<"3.8"', -] - -# pylint: disable=redefined-builtin; why license is a builtin anyway? -license = "LGPL" - -author = "Python Code Quality Authority" -author_email = "code-quality@python.org" -mailinglist = "mailto://%s" % author_email -web = "https://github.com/PyCQA/astroid" - -description = "An abstract syntax tree for Python with inference support." - -classifiers = [ - "Topic :: Software Development :: Libraries :: Python Modules", - "Topic :: Software Development :: Quality Assurance", - "Programming Language :: Python", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.5", - "Programming Language :: Python :: 3.6", - "Programming Language :: Python :: 3.7", - "Programming Language :: Python :: 3.8", - "Programming Language :: Python :: Implementation :: CPython", - "Programming Language :: Python :: Implementation :: PyPy", -] diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pycache__/__init__.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pycache__/__init__.cpython-38.pyc deleted file mode 100644 index d094255..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pycache__/__init__.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pycache__/__pkginfo__.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pycache__/__pkginfo__.cpython-38.pyc deleted file mode 100644 index af0fdc5..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pycache__/__pkginfo__.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pycache__/_ast.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pycache__/_ast.cpython-38.pyc deleted file mode 100644 index 22b0576..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pycache__/_ast.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pycache__/arguments.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pycache__/arguments.cpython-38.pyc deleted file mode 100644 index 84e44be..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pycache__/arguments.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pycache__/as_string.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pycache__/as_string.cpython-38.pyc deleted file mode 100644 index 408917c..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pycache__/as_string.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pycache__/bases.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pycache__/bases.cpython-38.pyc deleted file mode 100644 index 96c12de..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pycache__/bases.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pycache__/builder.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pycache__/builder.cpython-38.pyc deleted file mode 100644 index e0bdd80..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pycache__/builder.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pycache__/context.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pycache__/context.cpython-38.pyc deleted file mode 100644 index 3394f34..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pycache__/context.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pycache__/decorators.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pycache__/decorators.cpython-38.pyc deleted file mode 100644 index 6264ceb..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pycache__/decorators.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pycache__/exceptions.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pycache__/exceptions.cpython-38.pyc deleted file mode 100644 index 1c49d49..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pycache__/exceptions.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pycache__/helpers.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pycache__/helpers.cpython-38.pyc deleted file mode 100644 index 86a4d36..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pycache__/helpers.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pycache__/inference.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pycache__/inference.cpython-38.pyc deleted file mode 100644 index 454a8fe..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pycache__/inference.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pycache__/manager.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pycache__/manager.cpython-38.pyc deleted file mode 100644 index bb8f4d1..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pycache__/manager.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pycache__/mixins.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pycache__/mixins.cpython-38.pyc deleted file mode 100644 index d52a1d1..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pycache__/mixins.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pycache__/modutils.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pycache__/modutils.cpython-38.pyc deleted file mode 100644 index dc68874..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pycache__/modutils.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pycache__/node_classes.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pycache__/node_classes.cpython-38.pyc deleted file mode 100644 index af5ebe0..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pycache__/node_classes.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pycache__/nodes.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pycache__/nodes.cpython-38.pyc deleted file mode 100644 index 50f37f2..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pycache__/nodes.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pycache__/objects.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pycache__/objects.cpython-38.pyc deleted file mode 100644 index 88ee422..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pycache__/objects.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pycache__/protocols.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pycache__/protocols.cpython-38.pyc deleted file mode 100644 index be16842..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pycache__/protocols.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pycache__/raw_building.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pycache__/raw_building.cpython-38.pyc deleted file mode 100644 index f45eddc..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pycache__/raw_building.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pycache__/rebuilder.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pycache__/rebuilder.cpython-38.pyc deleted file mode 100644 index 548572b..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pycache__/rebuilder.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pycache__/scoped_nodes.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pycache__/scoped_nodes.cpython-38.pyc deleted file mode 100644 index 5722d1d..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pycache__/scoped_nodes.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pycache__/test_utils.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pycache__/test_utils.cpython-38.pyc deleted file mode 100644 index 77cea63..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pycache__/test_utils.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pycache__/transforms.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pycache__/transforms.cpython-38.pyc deleted file mode 100644 index c05cac0..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pycache__/transforms.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pycache__/util.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pycache__/util.cpython-38.pyc deleted file mode 100644 index 876dca0..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/__pycache__/util.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/_ast.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/_ast.py deleted file mode 100644 index 34b74c5..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/_ast.py +++ /dev/null @@ -1,131 +0,0 @@ -import ast -from collections import namedtuple -from functools import partial -from typing import Optional -import sys - -import astroid - -_ast_py3 = None -try: - import typed_ast.ast3 as _ast_py3 -except ImportError: - pass - - -PY38 = sys.version_info[:2] >= (3, 8) -if PY38: - # On Python 3.8, typed_ast was merged back into `ast` - _ast_py3 = ast - - -FunctionType = namedtuple("FunctionType", ["argtypes", "returns"]) - - -class ParserModule( - namedtuple( - "ParserModule", - [ - "module", - "unary_op_classes", - "cmp_op_classes", - "bool_op_classes", - "bin_op_classes", - "context_classes", - ], - ) -): - def parse(self, string: str, type_comments=True): - if self.module is _ast_py3: - if PY38: - parse_func = partial(self.module.parse, type_comments=type_comments) - else: - parse_func = partial( - self.module.parse, feature_version=sys.version_info.minor - ) - else: - parse_func = self.module.parse - return parse_func(string) - - -def parse_function_type_comment(type_comment: str) -> Optional[FunctionType]: - """Given a correct type comment, obtain a FunctionType object""" - if _ast_py3 is None: - return None - - func_type = _ast_py3.parse(type_comment, "", "func_type") - return FunctionType(argtypes=func_type.argtypes, returns=func_type.returns) - - -def get_parser_module(type_comments=True) -> ParserModule: - if not type_comments: - parser_module = ast - else: - parser_module = _ast_py3 - parser_module = parser_module or ast - - unary_op_classes = _unary_operators_from_module(parser_module) - cmp_op_classes = _compare_operators_from_module(parser_module) - bool_op_classes = _bool_operators_from_module(parser_module) - bin_op_classes = _binary_operators_from_module(parser_module) - context_classes = _contexts_from_module(parser_module) - - return ParserModule( - parser_module, - unary_op_classes, - cmp_op_classes, - bool_op_classes, - bin_op_classes, - context_classes, - ) - - -def _unary_operators_from_module(module): - return {module.UAdd: "+", module.USub: "-", module.Not: "not", module.Invert: "~"} - - -def _binary_operators_from_module(module): - binary_operators = { - module.Add: "+", - module.BitAnd: "&", - module.BitOr: "|", - module.BitXor: "^", - module.Div: "/", - module.FloorDiv: "//", - module.MatMult: "@", - module.Mod: "%", - module.Mult: "*", - module.Pow: "**", - module.Sub: "-", - module.LShift: "<<", - module.RShift: ">>", - } - return binary_operators - - -def _bool_operators_from_module(module): - return {module.And: "and", module.Or: "or"} - - -def _compare_operators_from_module(module): - return { - module.Eq: "==", - module.Gt: ">", - module.GtE: ">=", - module.In: "in", - module.Is: "is", - module.IsNot: "is not", - module.Lt: "<", - module.LtE: "<=", - module.NotEq: "!=", - module.NotIn: "not in", - } - - -def _contexts_from_module(module): - return { - module.Load: astroid.Load, - module.Store: astroid.Store, - module.Del: astroid.Del, - module.Param: astroid.Store, - } diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/arguments.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/arguments.py deleted file mode 100644 index 5f4d909..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/arguments.py +++ /dev/null @@ -1,300 +0,0 @@ -# Copyright (c) 2015-2016, 2018-2020 Claudiu Popa -# Copyright (c) 2015-2016 Ceridwen -# Copyright (c) 2018 Bryce Guinta -# Copyright (c) 2018 Nick Drozd -# Copyright (c) 2018 Anthony Sottile - -# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html -# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER - - -from astroid import bases -from astroid import context as contextmod -from astroid import exceptions -from astroid import nodes -from astroid import util - - -class CallSite: - """Class for understanding arguments passed into a call site - - It needs a call context, which contains the arguments and the - keyword arguments that were passed into a given call site. - In order to infer what an argument represents, call :meth:`infer_argument` - with the corresponding function node and the argument name. - - :param callcontext: - An instance of :class:`astroid.context.CallContext`, that holds - the arguments for the call site. - :param argument_context_map: - Additional contexts per node, passed in from :attr:`astroid.context.Context.extra_context` - :param context: - An instance of :class:`astroid.context.Context`. - """ - - def __init__(self, callcontext, argument_context_map=None, context=None): - if argument_context_map is None: - argument_context_map = {} - self.argument_context_map = argument_context_map - args = callcontext.args - keywords = callcontext.keywords - self.duplicated_keywords = set() - self._unpacked_args = self._unpack_args(args, context=context) - self._unpacked_kwargs = self._unpack_keywords(keywords, context=context) - - self.positional_arguments = [ - arg for arg in self._unpacked_args if arg is not util.Uninferable - ] - self.keyword_arguments = { - key: value - for key, value in self._unpacked_kwargs.items() - if value is not util.Uninferable - } - - @classmethod - def from_call(cls, call_node, context=None): - """Get a CallSite object from the given Call node. - - :param context: - An instance of :class:`astroid.context.Context` that will be used - to force a single inference path. - """ - - # Determine the callcontext from the given `context` object if any. - context = context or contextmod.InferenceContext() - callcontext = contextmod.CallContext(call_node.args, call_node.keywords) - return cls(callcontext, context=context) - - def has_invalid_arguments(self): - """Check if in the current CallSite were passed *invalid* arguments - - This can mean multiple things. For instance, if an unpacking - of an invalid object was passed, then this method will return True. - Other cases can be when the arguments can't be inferred by astroid, - for example, by passing objects which aren't known statically. - """ - return len(self.positional_arguments) != len(self._unpacked_args) - - def has_invalid_keywords(self): - """Check if in the current CallSite were passed *invalid* keyword arguments - - For instance, unpacking a dictionary with integer keys is invalid - (**{1:2}), because the keys must be strings, which will make this - method to return True. Other cases where this might return True if - objects which can't be inferred were passed. - """ - return len(self.keyword_arguments) != len(self._unpacked_kwargs) - - def _unpack_keywords(self, keywords, context=None): - values = {} - context = context or contextmod.InferenceContext() - context.extra_context = self.argument_context_map - for name, value in keywords: - if name is None: - # Then it's an unpacking operation (**) - try: - inferred = next(value.infer(context=context)) - except exceptions.InferenceError: - values[name] = util.Uninferable - continue - - if not isinstance(inferred, nodes.Dict): - # Not something we can work with. - values[name] = util.Uninferable - continue - - for dict_key, dict_value in inferred.items: - try: - dict_key = next(dict_key.infer(context=context)) - except exceptions.InferenceError: - values[name] = util.Uninferable - continue - if not isinstance(dict_key, nodes.Const): - values[name] = util.Uninferable - continue - if not isinstance(dict_key.value, str): - values[name] = util.Uninferable - continue - if dict_key.value in values: - # The name is already in the dictionary - values[dict_key.value] = util.Uninferable - self.duplicated_keywords.add(dict_key.value) - continue - values[dict_key.value] = dict_value - else: - values[name] = value - return values - - def _unpack_args(self, args, context=None): - values = [] - context = context or contextmod.InferenceContext() - context.extra_context = self.argument_context_map - for arg in args: - if isinstance(arg, nodes.Starred): - try: - inferred = next(arg.value.infer(context=context)) - except exceptions.InferenceError: - values.append(util.Uninferable) - continue - - if inferred is util.Uninferable: - values.append(util.Uninferable) - continue - if not hasattr(inferred, "elts"): - values.append(util.Uninferable) - continue - values.extend(inferred.elts) - else: - values.append(arg) - return values - - def infer_argument(self, funcnode, name, context): - """infer a function argument value according to the call context - - Arguments: - funcnode: The function being called. - name: The name of the argument whose value is being inferred. - context: Inference context object - """ - if name in self.duplicated_keywords: - raise exceptions.InferenceError( - "The arguments passed to {func!r} " " have duplicate keywords.", - call_site=self, - func=funcnode, - arg=name, - context=context, - ) - - # Look into the keywords first, maybe it's already there. - try: - return self.keyword_arguments[name].infer(context) - except KeyError: - pass - - # Too many arguments given and no variable arguments. - if len(self.positional_arguments) > len(funcnode.args.args): - if not funcnode.args.vararg: - raise exceptions.InferenceError( - "Too many positional arguments " - "passed to {func!r} that does " - "not have *args.", - call_site=self, - func=funcnode, - arg=name, - context=context, - ) - - positional = self.positional_arguments[: len(funcnode.args.args)] - vararg = self.positional_arguments[len(funcnode.args.args) :] - argindex = funcnode.args.find_argname(name)[0] - kwonlyargs = {arg.name for arg in funcnode.args.kwonlyargs} - kwargs = { - key: value - for key, value in self.keyword_arguments.items() - if key not in kwonlyargs - } - # If there are too few positionals compared to - # what the function expects to receive, check to see - # if the missing positional arguments were passed - # as keyword arguments and if so, place them into the - # positional args list. - if len(positional) < len(funcnode.args.args): - for func_arg in funcnode.args.args: - if func_arg.name in kwargs: - arg = kwargs.pop(func_arg.name) - positional.append(arg) - - if argindex is not None: - # 2. first argument of instance/class method - if argindex == 0 and funcnode.type in ("method", "classmethod"): - if context.boundnode is not None: - boundnode = context.boundnode - else: - # XXX can do better ? - boundnode = funcnode.parent.frame() - - if isinstance(boundnode, nodes.ClassDef): - # Verify that we're accessing a method - # of the metaclass through a class, as in - # `cls.metaclass_method`. In this case, the - # first argument is always the class. - method_scope = funcnode.parent.scope() - if method_scope is boundnode.metaclass(): - return iter((boundnode,)) - - if funcnode.type == "method": - if not isinstance(boundnode, bases.Instance): - boundnode = boundnode.instantiate_class() - return iter((boundnode,)) - if funcnode.type == "classmethod": - return iter((boundnode,)) - # if we have a method, extract one position - # from the index, so we'll take in account - # the extra parameter represented by `self` or `cls` - if funcnode.type in ("method", "classmethod"): - argindex -= 1 - # 2. search arg index - try: - return self.positional_arguments[argindex].infer(context) - except IndexError: - pass - - if funcnode.args.kwarg == name: - # It wants all the keywords that were passed into - # the call site. - if self.has_invalid_keywords(): - raise exceptions.InferenceError( - "Inference failed to find values for all keyword arguments " - "to {func!r}: {unpacked_kwargs!r} doesn't correspond to " - "{keyword_arguments!r}.", - keyword_arguments=self.keyword_arguments, - unpacked_kwargs=self._unpacked_kwargs, - call_site=self, - func=funcnode, - arg=name, - context=context, - ) - kwarg = nodes.Dict( - lineno=funcnode.args.lineno, - col_offset=funcnode.args.col_offset, - parent=funcnode.args, - ) - kwarg.postinit( - [(nodes.const_factory(key), value) for key, value in kwargs.items()] - ) - return iter((kwarg,)) - if funcnode.args.vararg == name: - # It wants all the args that were passed into - # the call site. - if self.has_invalid_arguments(): - raise exceptions.InferenceError( - "Inference failed to find values for all positional " - "arguments to {func!r}: {unpacked_args!r} doesn't " - "correspond to {positional_arguments!r}.", - positional_arguments=self.positional_arguments, - unpacked_args=self._unpacked_args, - call_site=self, - func=funcnode, - arg=name, - context=context, - ) - args = nodes.Tuple( - lineno=funcnode.args.lineno, - col_offset=funcnode.args.col_offset, - parent=funcnode.args, - ) - args.postinit(vararg) - return iter((args,)) - - # Check if it's a default parameter. - try: - return funcnode.args.default_value(name).infer(context) - except exceptions.NoDefault: - pass - raise exceptions.InferenceError( - "No value found for argument {name} to " "{func!r}", - call_site=self, - func=funcnode, - arg=name, - context=context, - ) diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/as_string.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/as_string.py deleted file mode 100644 index 653411f..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/as_string.py +++ /dev/null @@ -1,631 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright (c) 2009-2011, 2013-2014 LOGILAB S.A. (Paris, FRANCE) -# Copyright (c) 2010 Daniel Harding -# Copyright (c) 2013-2016, 2018-2020 Claudiu Popa -# Copyright (c) 2013-2014 Google, Inc. -# Copyright (c) 2015-2016 Ceridwen -# Copyright (c) 2016 Jared Garst -# Copyright (c) 2016 Jakub Wilk -# Copyright (c) 2017, 2019 Łukasz Rogalski -# Copyright (c) 2017 rr- -# Copyright (c) 2018 Serhiy Storchaka -# Copyright (c) 2018 Ville Skyttä -# Copyright (c) 2018 brendanator -# Copyright (c) 2018 Nick Drozd -# Copyright (c) 2019 Alex Hall -# Copyright (c) 2019 Hugo van Kemenade - -# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html -# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER - -"""This module renders Astroid nodes as string: - -* :func:`to_code` function return equivalent (hopefully valid) python string - -* :func:`dump` function return an internal representation of nodes found - in the tree, useful for debugging or understanding the tree structure -""" - -# pylint: disable=unused-argument - -DOC_NEWLINE = "\0" - - -class AsStringVisitor: - """Visitor to render an Astroid node as a valid python code string""" - - def __init__(self, indent): - self.indent = indent - - def __call__(self, node): - """Makes this visitor behave as a simple function""" - return node.accept(self).replace(DOC_NEWLINE, "\n") - - def _docs_dedent(self, doc): - """Stop newlines in docs being indented by self._stmt_list""" - return '\n%s"""%s"""' % (self.indent, doc.replace("\n", DOC_NEWLINE)) - - def _stmt_list(self, stmts, indent=True): - """return a list of nodes to string""" - stmts = "\n".join(nstr for nstr in [n.accept(self) for n in stmts] if nstr) - if indent: - return self.indent + stmts.replace("\n", "\n" + self.indent) - - return stmts - - def _precedence_parens(self, node, child, is_left=True): - """Wrap child in parens only if required to keep same semantics""" - if self._should_wrap(node, child, is_left): - return "(%s)" % child.accept(self) - - return child.accept(self) - - def _should_wrap(self, node, child, is_left): - """Wrap child if: - - it has lower precedence - - same precedence with position opposite to associativity direction - """ - node_precedence = node.op_precedence() - child_precedence = child.op_precedence() - - if node_precedence > child_precedence: - # 3 * (4 + 5) - return True - - if ( - node_precedence == child_precedence - and is_left != node.op_left_associative() - ): - # 3 - (4 - 5) - # (2**3)**4 - return True - - return False - - ## visit_ methods ########################################### - - def visit_await(self, node): - return "await %s" % node.value.accept(self) - - def visit_asyncwith(self, node): - return "async %s" % self.visit_with(node) - - def visit_asyncfor(self, node): - return "async %s" % self.visit_for(node) - - def visit_arguments(self, node): - """return an astroid.Function node as string""" - return node.format_args() - - def visit_assignattr(self, node): - """return an astroid.AssAttr node as string""" - return self.visit_attribute(node) - - def visit_assert(self, node): - """return an astroid.Assert node as string""" - if node.fail: - return "assert %s, %s" % (node.test.accept(self), node.fail.accept(self)) - return "assert %s" % node.test.accept(self) - - def visit_assignname(self, node): - """return an astroid.AssName node as string""" - return node.name - - def visit_assign(self, node): - """return an astroid.Assign node as string""" - lhs = " = ".join(n.accept(self) for n in node.targets) - return "%s = %s" % (lhs, node.value.accept(self)) - - def visit_augassign(self, node): - """return an astroid.AugAssign node as string""" - return "%s %s %s" % (node.target.accept(self), node.op, node.value.accept(self)) - - def visit_annassign(self, node): - """Return an astroid.AugAssign node as string""" - - target = node.target.accept(self) - annotation = node.annotation.accept(self) - if node.value is None: - return "%s: %s" % (target, annotation) - return "%s: %s = %s" % (target, annotation, node.value.accept(self)) - - def visit_repr(self, node): - """return an astroid.Repr node as string""" - return "`%s`" % node.value.accept(self) - - def visit_binop(self, node): - """return an astroid.BinOp node as string""" - left = self._precedence_parens(node, node.left) - right = self._precedence_parens(node, node.right, is_left=False) - if node.op == "**": - return "%s%s%s" % (left, node.op, right) - - return "%s %s %s" % (left, node.op, right) - - def visit_boolop(self, node): - """return an astroid.BoolOp node as string""" - values = ["%s" % self._precedence_parens(node, n) for n in node.values] - return (" %s " % node.op).join(values) - - def visit_break(self, node): - """return an astroid.Break node as string""" - return "break" - - def visit_call(self, node): - """return an astroid.Call node as string""" - expr_str = self._precedence_parens(node, node.func) - args = [arg.accept(self) for arg in node.args] - if node.keywords: - keywords = [kwarg.accept(self) for kwarg in node.keywords] - else: - keywords = [] - - args.extend(keywords) - return "%s(%s)" % (expr_str, ", ".join(args)) - - def visit_classdef(self, node): - """return an astroid.ClassDef node as string""" - decorate = node.decorators.accept(self) if node.decorators else "" - args = [n.accept(self) for n in node.bases] - if node._metaclass and not node.has_metaclass_hack(): - args.append("metaclass=" + node._metaclass.accept(self)) - args += [n.accept(self) for n in node.keywords] - args = "(%s)" % ", ".join(args) if args else "" - docs = self._docs_dedent(node.doc) if node.doc else "" - return "\n\n%sclass %s%s:%s\n%s\n" % ( - decorate, - node.name, - args, - docs, - self._stmt_list(node.body), - ) - - def visit_compare(self, node): - """return an astroid.Compare node as string""" - rhs_str = " ".join( - [ - "%s %s" % (op, self._precedence_parens(node, expr, is_left=False)) - for op, expr in node.ops - ] - ) - return "%s %s" % (self._precedence_parens(node, node.left), rhs_str) - - def visit_comprehension(self, node): - """return an astroid.Comprehension node as string""" - ifs = "".join(" if %s" % n.accept(self) for n in node.ifs) - generated = "for %s in %s%s" % ( - node.target.accept(self), - node.iter.accept(self), - ifs, - ) - return "%s%s" % ("async " if node.is_async else "", generated) - - def visit_const(self, node): - """return an astroid.Const node as string""" - if node.value is Ellipsis: - return "..." - return repr(node.value) - - def visit_continue(self, node): - """return an astroid.Continue node as string""" - return "continue" - - def visit_delete(self, node): # XXX check if correct - """return an astroid.Delete node as string""" - return "del %s" % ", ".join(child.accept(self) for child in node.targets) - - def visit_delattr(self, node): - """return an astroid.DelAttr node as string""" - return self.visit_attribute(node) - - def visit_delname(self, node): - """return an astroid.DelName node as string""" - return node.name - - def visit_decorators(self, node): - """return an astroid.Decorators node as string""" - return "@%s\n" % "\n@".join(item.accept(self) for item in node.nodes) - - def visit_dict(self, node): - """return an astroid.Dict node as string""" - return "{%s}" % ", ".join(self._visit_dict(node)) - - def _visit_dict(self, node): - for key, value in node.items: - key = key.accept(self) - value = value.accept(self) - if key == "**": - # It can only be a DictUnpack node. - yield key + value - else: - yield "%s: %s" % (key, value) - - def visit_dictunpack(self, node): - return "**" - - def visit_dictcomp(self, node): - """return an astroid.DictComp node as string""" - return "{%s: %s %s}" % ( - node.key.accept(self), - node.value.accept(self), - " ".join(n.accept(self) for n in node.generators), - ) - - def visit_expr(self, node): - """return an astroid.Discard node as string""" - return node.value.accept(self) - - def visit_emptynode(self, node): - """dummy method for visiting an Empty node""" - return "" - - def visit_excepthandler(self, node): - if node.type: - if node.name: - excs = "except %s as %s" % ( - node.type.accept(self), - node.name.accept(self), - ) - else: - excs = "except %s" % node.type.accept(self) - else: - excs = "except" - return "%s:\n%s" % (excs, self._stmt_list(node.body)) - - def visit_ellipsis(self, node): - """return an astroid.Ellipsis node as string""" - return "..." - - def visit_empty(self, node): - """return an Empty node as string""" - return "" - - def visit_exec(self, node): - """return an astroid.Exec node as string""" - if node.locals: - return "exec %s in %s, %s" % ( - node.expr.accept(self), - node.locals.accept(self), - node.globals.accept(self), - ) - if node.globals: - return "exec %s in %s" % (node.expr.accept(self), node.globals.accept(self)) - return "exec %s" % node.expr.accept(self) - - def visit_extslice(self, node): - """return an astroid.ExtSlice node as string""" - return ", ".join(dim.accept(self) for dim in node.dims) - - def visit_for(self, node): - """return an astroid.For node as string""" - fors = "for %s in %s:\n%s" % ( - node.target.accept(self), - node.iter.accept(self), - self._stmt_list(node.body), - ) - if node.orelse: - fors = "%s\nelse:\n%s" % (fors, self._stmt_list(node.orelse)) - return fors - - def visit_importfrom(self, node): - """return an astroid.ImportFrom node as string""" - return "from %s import %s" % ( - "." * (node.level or 0) + node.modname, - _import_string(node.names), - ) - - def visit_joinedstr(self, node): - string = "".join( - # Use repr on the string literal parts - # to get proper escapes, e.g. \n, \\, \" - # But strip the quotes off the ends - # (they will always be one character: ' or ") - repr(value.value)[1:-1] - # Literal braces must be doubled to escape them - .replace("{", "{{").replace("}", "}}") - # Each value in values is either a string literal (Const) - # or a FormattedValue - if type(value).__name__ == "Const" else value.accept(self) - for value in node.values - ) - - # Try to find surrounding quotes that don't appear at all in the string. - # Because the formatted values inside {} can't contain backslash (\) - # using a triple quote is sometimes necessary - for quote in ["'", '"', '"""', "'''"]: - if quote not in string: - break - - return "f" + quote + string + quote - - def visit_formattedvalue(self, node): - result = node.value.accept(self) - if node.conversion and node.conversion >= 0: - # e.g. if node.conversion == 114: result += "!r" - result += "!" + chr(node.conversion) - if node.format_spec: - # The format spec is itself a JoinedString, i.e. an f-string - # We strip the f and quotes of the ends - result += ":" + node.format_spec.accept(self)[2:-1] - return "{%s}" % result - - def handle_functiondef(self, node, keyword): - """return a (possibly async) function definition node as string""" - decorate = node.decorators.accept(self) if node.decorators else "" - docs = self._docs_dedent(node.doc) if node.doc else "" - trailer = ":" - if node.returns: - return_annotation = " -> " + node.returns.as_string() - trailer = return_annotation + ":" - def_format = "\n%s%s %s(%s)%s%s\n%s" - return def_format % ( - decorate, - keyword, - node.name, - node.args.accept(self), - trailer, - docs, - self._stmt_list(node.body), - ) - - def visit_functiondef(self, node): - """return an astroid.FunctionDef node as string""" - return self.handle_functiondef(node, "def") - - def visit_asyncfunctiondef(self, node): - """return an astroid.AsyncFunction node as string""" - return self.handle_functiondef(node, "async def") - - def visit_generatorexp(self, node): - """return an astroid.GeneratorExp node as string""" - return "(%s %s)" % ( - node.elt.accept(self), - " ".join(n.accept(self) for n in node.generators), - ) - - def visit_attribute(self, node): - """return an astroid.Getattr node as string""" - left = self._precedence_parens(node, node.expr) - if left.isdigit(): - left = "(%s)" % left - return "%s.%s" % (left, node.attrname) - - def visit_global(self, node): - """return an astroid.Global node as string""" - return "global %s" % ", ".join(node.names) - - def visit_if(self, node): - """return an astroid.If node as string""" - ifs = ["if %s:\n%s" % (node.test.accept(self), self._stmt_list(node.body))] - if node.has_elif_block(): - ifs.append("el%s" % self._stmt_list(node.orelse, indent=False)) - elif node.orelse: - ifs.append("else:\n%s" % self._stmt_list(node.orelse)) - return "\n".join(ifs) - - def visit_ifexp(self, node): - """return an astroid.IfExp node as string""" - return "%s if %s else %s" % ( - self._precedence_parens(node, node.body, is_left=True), - self._precedence_parens(node, node.test, is_left=True), - self._precedence_parens(node, node.orelse, is_left=False), - ) - - def visit_import(self, node): - """return an astroid.Import node as string""" - return "import %s" % _import_string(node.names) - - def visit_keyword(self, node): - """return an astroid.Keyword node as string""" - if node.arg is None: - return "**%s" % node.value.accept(self) - return "%s=%s" % (node.arg, node.value.accept(self)) - - def visit_lambda(self, node): - """return an astroid.Lambda node as string""" - args = node.args.accept(self) - body = node.body.accept(self) - if args: - return "lambda %s: %s" % (args, body) - - return "lambda: %s" % body - - def visit_list(self, node): - """return an astroid.List node as string""" - return "[%s]" % ", ".join(child.accept(self) for child in node.elts) - - def visit_listcomp(self, node): - """return an astroid.ListComp node as string""" - return "[%s %s]" % ( - node.elt.accept(self), - " ".join(n.accept(self) for n in node.generators), - ) - - def visit_module(self, node): - """return an astroid.Module node as string""" - docs = '"""%s"""\n\n' % node.doc if node.doc else "" - return docs + "\n".join(n.accept(self) for n in node.body) + "\n\n" - - def visit_name(self, node): - """return an astroid.Name node as string""" - return node.name - - def visit_namedexpr(self, node): - """Return an assignment expression node as string""" - target = node.target.accept(self) - value = node.value.accept(self) - return "%s := %s" % (target, value) - - def visit_nonlocal(self, node): - """return an astroid.Nonlocal node as string""" - return "nonlocal %s" % ", ".join(node.names) - - def visit_pass(self, node): - """return an astroid.Pass node as string""" - return "pass" - - def visit_print(self, node): - """return an astroid.Print node as string""" - nodes = ", ".join(n.accept(self) for n in node.values) - if not node.nl: - nodes = "%s," % nodes - if node.dest: - return "print >> %s, %s" % (node.dest.accept(self), nodes) - return "print %s" % nodes - - def visit_raise(self, node): - """return an astroid.Raise node as string""" - if node.exc: - if node.cause: - return "raise %s from %s" % ( - node.exc.accept(self), - node.cause.accept(self), - ) - return "raise %s" % node.exc.accept(self) - return "raise" - - def visit_return(self, node): - """return an astroid.Return node as string""" - if node.is_tuple_return() and len(node.value.elts) > 1: - elts = [child.accept(self) for child in node.value.elts] - return "return %s" % ", ".join(elts) - - if node.value: - return "return %s" % node.value.accept(self) - - return "return" - - def visit_index(self, node): - """return an astroid.Index node as string""" - return node.value.accept(self) - - def visit_set(self, node): - """return an astroid.Set node as string""" - return "{%s}" % ", ".join(child.accept(self) for child in node.elts) - - def visit_setcomp(self, node): - """return an astroid.SetComp node as string""" - return "{%s %s}" % ( - node.elt.accept(self), - " ".join(n.accept(self) for n in node.generators), - ) - - def visit_slice(self, node): - """return an astroid.Slice node as string""" - lower = node.lower.accept(self) if node.lower else "" - upper = node.upper.accept(self) if node.upper else "" - step = node.step.accept(self) if node.step else "" - if step: - return "%s:%s:%s" % (lower, upper, step) - return "%s:%s" % (lower, upper) - - def visit_subscript(self, node): - """return an astroid.Subscript node as string""" - idx = node.slice - if idx.__class__.__name__.lower() == "index": - idx = idx.value - idxstr = idx.accept(self) - if idx.__class__.__name__.lower() == "tuple" and idx.elts: - # Remove parenthesis in tuple and extended slice. - # a[(::1, 1:)] is not valid syntax. - idxstr = idxstr[1:-1] - return "%s[%s]" % (self._precedence_parens(node, node.value), idxstr) - - def visit_tryexcept(self, node): - """return an astroid.TryExcept node as string""" - trys = ["try:\n%s" % self._stmt_list(node.body)] - for handler in node.handlers: - trys.append(handler.accept(self)) - if node.orelse: - trys.append("else:\n%s" % self._stmt_list(node.orelse)) - return "\n".join(trys) - - def visit_tryfinally(self, node): - """return an astroid.TryFinally node as string""" - return "try:\n%s\nfinally:\n%s" % ( - self._stmt_list(node.body), - self._stmt_list(node.finalbody), - ) - - def visit_tuple(self, node): - """return an astroid.Tuple node as string""" - if len(node.elts) == 1: - return "(%s, )" % node.elts[0].accept(self) - return "(%s)" % ", ".join(child.accept(self) for child in node.elts) - - def visit_unaryop(self, node): - """return an astroid.UnaryOp node as string""" - if node.op == "not": - operator = "not " - else: - operator = node.op - return "%s%s" % (operator, self._precedence_parens(node, node.operand)) - - def visit_while(self, node): - """return an astroid.While node as string""" - whiles = "while %s:\n%s" % (node.test.accept(self), self._stmt_list(node.body)) - if node.orelse: - whiles = "%s\nelse:\n%s" % (whiles, self._stmt_list(node.orelse)) - return whiles - - def visit_with(self, node): # 'with' without 'as' is possible - """return an astroid.With node as string""" - items = ", ".join( - ("%s" % expr.accept(self)) + (vars and " as %s" % (vars.accept(self)) or "") - for expr, vars in node.items - ) - return "with %s:\n%s" % (items, self._stmt_list(node.body)) - - def visit_yield(self, node): - """yield an ast.Yield node as string""" - yi_val = (" " + node.value.accept(self)) if node.value else "" - expr = "yield" + yi_val - if node.parent.is_statement: - return expr - - return "(%s)" % (expr,) - - def visit_yieldfrom(self, node): - """ Return an astroid.YieldFrom node as string. """ - yi_val = (" " + node.value.accept(self)) if node.value else "" - expr = "yield from" + yi_val - if node.parent.is_statement: - return expr - - return "(%s)" % (expr,) - - def visit_starred(self, node): - """return Starred node as string""" - return "*" + node.value.accept(self) - - # These aren't for real AST nodes, but for inference objects. - - def visit_frozenset(self, node): - return node.parent.accept(self) - - def visit_super(self, node): - return node.parent.accept(self) - - def visit_uninferable(self, node): - return str(node) - - def visit_property(self, node): - return node.function.accept(self) - - def visit_evaluatedobject(self, node): - return node.original.accept(self) - - -def _import_string(names): - """return a list of (name, asname) formatted as a string""" - _names = [] - for name, asname in names: - if asname is not None: - _names.append("%s as %s" % (name, asname)) - else: - _names.append(name) - return ", ".join(_names) - - -# This sets the default indent to 4 spaces. -to_code = AsStringVisitor(" ") diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/bases.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/bases.py deleted file mode 100644 index 9c74303..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/bases.py +++ /dev/null @@ -1,548 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright (c) 2009-2011, 2013-2014 LOGILAB S.A. (Paris, FRANCE) -# Copyright (c) 2012 FELD Boris -# Copyright (c) 2014-2020 Claudiu Popa -# Copyright (c) 2014 Google, Inc. -# Copyright (c) 2014 Eevee (Alex Munroe) -# Copyright (c) 2015-2016 Ceridwen -# Copyright (c) 2015 Florian Bruhin -# Copyright (c) 2016-2017 Derek Gustafson -# Copyright (c) 2017 Calen Pennington -# Copyright (c) 2018-2019 hippo91 -# Copyright (c) 2018 Ville Skyttä -# Copyright (c) 2018 Bryce Guinta -# Copyright (c) 2018 Nick Drozd -# Copyright (c) 2018 Daniel Colascione -# Copyright (c) 2019 Hugo van Kemenade - -# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html -# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER - -"""This module contains base classes and functions for the nodes and some -inference utils. -""" - -import builtins -import collections - -from astroid import context as contextmod -from astroid import exceptions -from astroid import util - -objectmodel = util.lazy_import("interpreter.objectmodel") -helpers = util.lazy_import("helpers") -BUILTINS = builtins.__name__ -manager = util.lazy_import("manager") -MANAGER = manager.AstroidManager() - -# TODO: check if needs special treatment -BUILTINS = "builtins" -BOOL_SPECIAL_METHOD = "__bool__" - -PROPERTIES = {BUILTINS + ".property", "abc.abstractproperty"} -# List of possible property names. We use this list in order -# to see if a method is a property or not. This should be -# pretty reliable and fast, the alternative being to check each -# decorator to see if its a real property-like descriptor, which -# can be too complicated. -# Also, these aren't qualified, because each project can -# define them, we shouldn't expect to know every possible -# property-like decorator! -POSSIBLE_PROPERTIES = { - "cached_property", - "cachedproperty", - "lazyproperty", - "lazy_property", - "reify", - "lazyattribute", - "lazy_attribute", - "LazyProperty", - "lazy", - "cache_readonly", -} - - -def _is_property(meth, context=None): - decoratornames = meth.decoratornames(context=context) - if PROPERTIES.intersection(decoratornames): - return True - stripped = { - name.split(".")[-1] for name in decoratornames if name is not util.Uninferable - } - if any(name in stripped for name in POSSIBLE_PROPERTIES): - return True - - # Lookup for subclasses of *property* - if not meth.decorators: - return False - for decorator in meth.decorators.nodes or (): - inferred = helpers.safe_infer(decorator, context=context) - if inferred is None or inferred is util.Uninferable: - continue - if inferred.__class__.__name__ == "ClassDef": - for base_class in inferred.bases: - if base_class.__class__.__name__ != "Name": - continue - module, _ = base_class.lookup(base_class.name) - if module.name == BUILTINS and base_class.name == "property": - return True - - return False - - -class Proxy: - """a simple proxy object - - Note: - - Subclasses of this object will need a custom __getattr__ - if new instance attributes are created. See the Const class - """ - - _proxied = None # proxied object may be set by class or by instance - - def __init__(self, proxied=None): - if proxied is not None: - self._proxied = proxied - - def __getattr__(self, name): - if name == "_proxied": - return getattr(self.__class__, "_proxied") - if name in self.__dict__: - return self.__dict__[name] - return getattr(self._proxied, name) - - def infer(self, context=None): - yield self - - -def _infer_stmts(stmts, context, frame=None): - """Return an iterator on statements inferred by each statement in *stmts*.""" - inferred = False - if context is not None: - name = context.lookupname - context = context.clone() - else: - name = None - context = contextmod.InferenceContext() - - for stmt in stmts: - if stmt is util.Uninferable: - yield stmt - inferred = True - continue - context.lookupname = stmt._infer_name(frame, name) - try: - for inferred in stmt.infer(context=context): - yield inferred - inferred = True - except exceptions.NameInferenceError: - continue - except exceptions.InferenceError: - yield util.Uninferable - inferred = True - if not inferred: - raise exceptions.InferenceError( - "Inference failed for all members of {stmts!r}.", - stmts=stmts, - frame=frame, - context=context, - ) - - -def _infer_method_result_truth(instance, method_name, context): - # Get the method from the instance and try to infer - # its return's truth value. - meth = next(instance.igetattr(method_name, context=context), None) - if meth and hasattr(meth, "infer_call_result"): - if not meth.callable(): - return util.Uninferable - try: - for value in meth.infer_call_result(instance, context=context): - if value is util.Uninferable: - return value - - inferred = next(value.infer(context=context)) - return inferred.bool_value() - except exceptions.InferenceError: - pass - return util.Uninferable - - -class BaseInstance(Proxy): - """An instance base class, which provides lookup methods for potential instances.""" - - special_attributes = None - - def display_type(self): - return "Instance of" - - def getattr(self, name, context=None, lookupclass=True): - try: - values = self._proxied.instance_attr(name, context) - except exceptions.AttributeInferenceError as exc: - if self.special_attributes and name in self.special_attributes: - return [self.special_attributes.lookup(name)] - - if lookupclass: - # Class attributes not available through the instance - # unless they are explicitly defined. - return self._proxied.getattr(name, context, class_context=False) - - raise exceptions.AttributeInferenceError( - target=self, attribute=name, context=context - ) from exc - # since we've no context information, return matching class members as - # well - if lookupclass: - try: - return values + self._proxied.getattr( - name, context, class_context=False - ) - except exceptions.AttributeInferenceError: - pass - return values - - def igetattr(self, name, context=None): - """inferred getattr""" - if not context: - context = contextmod.InferenceContext() - try: - # avoid recursively inferring the same attr on the same class - if context.push((self._proxied, name)): - raise exceptions.InferenceError( - message="Cannot infer the same attribute again", - node=self, - context=context, - ) - - # XXX frame should be self._proxied, or not ? - get_attr = self.getattr(name, context, lookupclass=False) - yield from _infer_stmts( - self._wrap_attr(get_attr, context), context, frame=self - ) - except exceptions.AttributeInferenceError as error: - try: - # fallback to class.igetattr since it has some logic to handle - # descriptors - # But only if the _proxied is the Class. - if self._proxied.__class__.__name__ != "ClassDef": - raise - attrs = self._proxied.igetattr(name, context, class_context=False) - yield from self._wrap_attr(attrs, context) - except exceptions.AttributeInferenceError as error: - raise exceptions.InferenceError(**vars(error)) from error - - def _wrap_attr(self, attrs, context=None): - """wrap bound methods of attrs in a InstanceMethod proxies""" - for attr in attrs: - if isinstance(attr, UnboundMethod): - if _is_property(attr): - yield from attr.infer_call_result(self, context) - else: - yield BoundMethod(attr, self) - elif hasattr(attr, "name") and attr.name == "": - if attr.args.arguments and attr.args.arguments[0].name == "self": - yield BoundMethod(attr, self) - continue - yield attr - else: - yield attr - - def infer_call_result(self, caller, context=None): - """infer what a class instance is returning when called""" - context = contextmod.bind_context_to_node(context, self) - inferred = False - for node in self._proxied.igetattr("__call__", context): - if node is util.Uninferable or not node.callable(): - continue - for res in node.infer_call_result(caller, context): - inferred = True - yield res - if not inferred: - raise exceptions.InferenceError(node=self, caller=caller, context=context) - - -class Instance(BaseInstance): - """A special node representing a class instance.""" - - # pylint: disable=unnecessary-lambda - special_attributes = util.lazy_descriptor(lambda: objectmodel.InstanceModel()) - - def __repr__(self): - return "" % ( - self._proxied.root().name, - self._proxied.name, - id(self), - ) - - def __str__(self): - return "Instance of %s.%s" % (self._proxied.root().name, self._proxied.name) - - def callable(self): - try: - self._proxied.getattr("__call__", class_context=False) - return True - except exceptions.AttributeInferenceError: - return False - - def pytype(self): - return self._proxied.qname() - - def display_type(self): - return "Instance of" - - def bool_value(self, context=None): - """Infer the truth value for an Instance - - The truth value of an instance is determined by these conditions: - - * if it implements __bool__ on Python 3 or __nonzero__ - on Python 2, then its bool value will be determined by - calling this special method and checking its result. - * when this method is not defined, __len__() is called, if it - is defined, and the object is considered true if its result is - nonzero. If a class defines neither __len__() nor __bool__(), - all its instances are considered true. - """ - context = context or contextmod.InferenceContext() - context.callcontext = contextmod.CallContext(args=[]) - context.boundnode = self - - try: - result = _infer_method_result_truth(self, BOOL_SPECIAL_METHOD, context) - except (exceptions.InferenceError, exceptions.AttributeInferenceError): - # Fallback to __len__. - try: - result = _infer_method_result_truth(self, "__len__", context) - except (exceptions.AttributeInferenceError, exceptions.InferenceError): - return True - return result - - # This is set in inference.py. - def getitem(self, index, context=None): - pass - - -class UnboundMethod(Proxy): - """a special node representing a method not bound to an instance""" - - # pylint: disable=unnecessary-lambda - special_attributes = util.lazy_descriptor(lambda: objectmodel.UnboundMethodModel()) - - def __repr__(self): - frame = self._proxied.parent.frame() - return "<%s %s of %s at 0x%s" % ( - self.__class__.__name__, - self._proxied.name, - frame.qname(), - id(self), - ) - - def implicit_parameters(self): - return 0 - - def is_bound(self): - return False - - def getattr(self, name, context=None): - if name in self.special_attributes: - return [self.special_attributes.lookup(name)] - return self._proxied.getattr(name, context) - - def igetattr(self, name, context=None): - if name in self.special_attributes: - return iter((self.special_attributes.lookup(name),)) - return self._proxied.igetattr(name, context) - - def infer_call_result(self, caller, context): - """ - The boundnode of the regular context with a function called - on ``object.__new__`` will be of type ``object``, - which is incorrect for the argument in general. - If no context is given the ``object.__new__`` call argument will - correctly inferred except when inside a call that requires - the additional context (such as a classmethod) of the boundnode - to determine which class the method was called from - """ - - # If we're unbound method __new__ of builtin object, the result is an - # instance of the class given as first argument. - if ( - self._proxied.name == "__new__" - and self._proxied.parent.frame().qname() == "%s.object" % BUILTINS - ): - if caller.args: - node_context = context.extra_context.get(caller.args[0]) - infer = caller.args[0].infer(context=node_context) - else: - infer = [] - return (Instance(x) if x is not util.Uninferable else x for x in infer) - return self._proxied.infer_call_result(caller, context) - - def bool_value(self, context=None): - return True - - -class BoundMethod(UnboundMethod): - """a special node representing a method bound to an instance""" - - # pylint: disable=unnecessary-lambda - special_attributes = util.lazy_descriptor(lambda: objectmodel.BoundMethodModel()) - - def __init__(self, proxy, bound): - UnboundMethod.__init__(self, proxy) - self.bound = bound - - def implicit_parameters(self): - if self.name == "__new__": - # __new__ acts as a classmethod but the class argument is not implicit. - return 0 - return 1 - - def is_bound(self): - return True - - def _infer_type_new_call(self, caller, context): - """Try to infer what type.__new__(mcs, name, bases, attrs) returns. - - In order for such call to be valid, the metaclass needs to be - a subtype of ``type``, the name needs to be a string, the bases - needs to be a tuple of classes - """ - # pylint: disable=import-outside-toplevel; circular import - from astroid import node_classes - - # Verify the metaclass - mcs = next(caller.args[0].infer(context=context)) - if mcs.__class__.__name__ != "ClassDef": - # Not a valid first argument. - return None - if not mcs.is_subtype_of("%s.type" % BUILTINS): - # Not a valid metaclass. - return None - - # Verify the name - name = next(caller.args[1].infer(context=context)) - if name.__class__.__name__ != "Const": - # Not a valid name, needs to be a const. - return None - if not isinstance(name.value, str): - # Needs to be a string. - return None - - # Verify the bases - bases = next(caller.args[2].infer(context=context)) - if bases.__class__.__name__ != "Tuple": - # Needs to be a tuple. - return None - inferred_bases = [next(elt.infer(context=context)) for elt in bases.elts] - if any(base.__class__.__name__ != "ClassDef" for base in inferred_bases): - # All the bases needs to be Classes - return None - - # Verify the attributes. - attrs = next(caller.args[3].infer(context=context)) - if attrs.__class__.__name__ != "Dict": - # Needs to be a dictionary. - return None - cls_locals = collections.defaultdict(list) - for key, value in attrs.items: - key = next(key.infer(context=context)) - value = next(value.infer(context=context)) - # Ignore non string keys - if key.__class__.__name__ == "Const" and isinstance(key.value, str): - cls_locals[key.value].append(value) - - # Build the class from now. - cls = mcs.__class__( - name=name.value, - lineno=caller.lineno, - col_offset=caller.col_offset, - parent=caller, - ) - empty = node_classes.Pass() - cls.postinit( - bases=bases.elts, - body=[empty], - decorators=[], - newstyle=True, - metaclass=mcs, - keywords=[], - ) - cls.locals = cls_locals - return cls - - def infer_call_result(self, caller, context=None): - context = contextmod.bind_context_to_node(context, self.bound) - if ( - self.bound.__class__.__name__ == "ClassDef" - and self.bound.name == "type" - and self.name == "__new__" - and len(caller.args) == 4 - ): - # Check if we have a ``type.__new__(mcs, name, bases, attrs)`` call. - new_cls = self._infer_type_new_call(caller, context) - if new_cls: - return iter((new_cls,)) - - return super().infer_call_result(caller, context) - - def bool_value(self, context=None): - return True - - -class Generator(BaseInstance): - """a special node representing a generator. - - Proxied class is set once for all in raw_building. - """ - - # pylint: disable=unnecessary-lambda - special_attributes = util.lazy_descriptor(lambda: objectmodel.GeneratorModel()) - - # pylint: disable=super-init-not-called - def __init__(self, parent=None): - self.parent = parent - - def callable(self): - return False - - def pytype(self): - return "%s.generator" % BUILTINS - - def display_type(self): - return "Generator" - - def bool_value(self, context=None): - return True - - def __repr__(self): - return "" % ( - self._proxied.name, - self.lineno, - id(self), - ) - - def __str__(self): - return "Generator(%s)" % (self._proxied.name) - - -class AsyncGenerator(Generator): - """Special node representing an async generator""" - - def pytype(self): - return "%s.async_generator" % BUILTINS - - def display_type(self): - return "AsyncGenerator" - - def __repr__(self): - return "" % ( - self._proxied.name, - self.lineno, - id(self), - ) - - def __str__(self): - return "AsyncGenerator(%s)" % (self._proxied.name) diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_argparse.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_argparse.cpython-38.pyc deleted file mode 100644 index 9134a27..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_argparse.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_attrs.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_attrs.cpython-38.pyc deleted file mode 100644 index 02f68bf..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_attrs.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_boto3.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_boto3.cpython-38.pyc deleted file mode 100644 index 03475a8..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_boto3.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_builtin_inference.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_builtin_inference.cpython-38.pyc deleted file mode 100644 index 13e18d1..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_builtin_inference.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_collections.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_collections.cpython-38.pyc deleted file mode 100644 index 0372f5b..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_collections.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_crypt.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_crypt.cpython-38.pyc deleted file mode 100644 index 996c719..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_crypt.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_curses.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_curses.cpython-38.pyc deleted file mode 100644 index 5da9bec..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_curses.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_dataclasses.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_dataclasses.cpython-38.pyc deleted file mode 100644 index c1fc689..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_dataclasses.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_dateutil.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_dateutil.cpython-38.pyc deleted file mode 100644 index 4b773af..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_dateutil.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_fstrings.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_fstrings.cpython-38.pyc deleted file mode 100644 index aa0fa68..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_fstrings.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_functools.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_functools.cpython-38.pyc deleted file mode 100644 index e7fe25f..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_functools.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_gi.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_gi.cpython-38.pyc deleted file mode 100644 index 3d68f18..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_gi.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_hashlib.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_hashlib.cpython-38.pyc deleted file mode 100644 index 37d85fe..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_hashlib.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_http.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_http.cpython-38.pyc deleted file mode 100644 index 8cc6f4f..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_http.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_io.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_io.cpython-38.pyc deleted file mode 100644 index 5d2df95..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_io.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_mechanize.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_mechanize.cpython-38.pyc deleted file mode 100644 index 98a0475..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_mechanize.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_multiprocessing.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_multiprocessing.cpython-38.pyc deleted file mode 100644 index 44a4f6d..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_multiprocessing.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_namedtuple_enum.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_namedtuple_enum.cpython-38.pyc deleted file mode 100644 index c042bfb..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_namedtuple_enum.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_nose.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_nose.cpython-38.pyc deleted file mode 100644 index fc53e40..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_nose.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_numpy_core_fromnumeric.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_numpy_core_fromnumeric.cpython-38.pyc deleted file mode 100644 index 2712340..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_numpy_core_fromnumeric.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_numpy_core_function_base.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_numpy_core_function_base.cpython-38.pyc deleted file mode 100644 index 8dccb73..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_numpy_core_function_base.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_numpy_core_multiarray.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_numpy_core_multiarray.cpython-38.pyc deleted file mode 100644 index 45ba50d..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_numpy_core_multiarray.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_numpy_core_numeric.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_numpy_core_numeric.cpython-38.pyc deleted file mode 100644 index 357ff22..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_numpy_core_numeric.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_numpy_core_numerictypes.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_numpy_core_numerictypes.cpython-38.pyc deleted file mode 100644 index 50c94a9..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_numpy_core_numerictypes.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_numpy_core_umath.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_numpy_core_umath.cpython-38.pyc deleted file mode 100644 index 500362f..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_numpy_core_umath.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_numpy_ndarray.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_numpy_ndarray.cpython-38.pyc deleted file mode 100644 index a1879a3..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_numpy_ndarray.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_numpy_random_mtrand.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_numpy_random_mtrand.cpython-38.pyc deleted file mode 100644 index a5de3c7..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_numpy_random_mtrand.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_numpy_utils.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_numpy_utils.cpython-38.pyc deleted file mode 100644 index aea3404..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_numpy_utils.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_pkg_resources.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_pkg_resources.cpython-38.pyc deleted file mode 100644 index 4376f5b..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_pkg_resources.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_pytest.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_pytest.cpython-38.pyc deleted file mode 100644 index a936bda..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_pytest.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_qt.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_qt.cpython-38.pyc deleted file mode 100644 index a448873..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_qt.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_random.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_random.cpython-38.pyc deleted file mode 100644 index bdda49c..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_random.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_re.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_re.cpython-38.pyc deleted file mode 100644 index f05641b..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_re.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_responses.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_responses.cpython-38.pyc deleted file mode 100644 index 5483699..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_responses.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_scipy_signal.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_scipy_signal.cpython-38.pyc deleted file mode 100644 index 47748df..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_scipy_signal.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_six.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_six.cpython-38.pyc deleted file mode 100644 index 5622f52..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_six.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_ssl.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_ssl.cpython-38.pyc deleted file mode 100644 index 3dac441..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_ssl.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_subprocess.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_subprocess.cpython-38.pyc deleted file mode 100644 index cd25aae..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_subprocess.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_threading.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_threading.cpython-38.pyc deleted file mode 100644 index 228aee8..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_threading.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_typing.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_typing.cpython-38.pyc deleted file mode 100644 index 28235dd..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_typing.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_uuid.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_uuid.cpython-38.pyc deleted file mode 100644 index 63fc002..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/__pycache__/brain_uuid.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_argparse.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_argparse.py deleted file mode 100644 index 6a7556f..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_argparse.py +++ /dev/null @@ -1,33 +0,0 @@ -from astroid import MANAGER, arguments, nodes, inference_tip, UseInferenceDefault - - -def infer_namespace(node, context=None): - callsite = arguments.CallSite.from_call(node, context=context) - if not callsite.keyword_arguments: - # Cannot make sense of it. - raise UseInferenceDefault() - - class_node = nodes.ClassDef("Namespace", "docstring") - class_node.parent = node.parent - for attr in set(callsite.keyword_arguments): - fake_node = nodes.EmptyNode() - fake_node.parent = class_node - fake_node.attrname = attr - class_node.instance_attrs[attr] = [fake_node] - return iter((class_node.instantiate_class(),)) - - -def _looks_like_namespace(node): - func = node.func - if isinstance(func, nodes.Attribute): - return ( - func.attrname == "Namespace" - and isinstance(func.expr, nodes.Name) - and func.expr.name == "argparse" - ) - return False - - -MANAGER.register_transform( - nodes.Call, inference_tip(infer_namespace), _looks_like_namespace -) diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_attrs.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_attrs.py deleted file mode 100644 index 670736f..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_attrs.py +++ /dev/null @@ -1,65 +0,0 @@ -# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html -# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER -""" -Astroid hook for the attrs library - -Without this hook pylint reports unsupported-assignment-operation -for attrs classes -""" - -import astroid -from astroid import MANAGER - - -ATTRIB_NAMES = frozenset(("attr.ib", "attrib", "attr.attrib")) -ATTRS_NAMES = frozenset(("attr.s", "attrs", "attr.attrs", "attr.attributes")) - - -def is_decorated_with_attrs(node, decorator_names=ATTRS_NAMES): - """Return True if a decorated node has - an attr decorator applied.""" - if not node.decorators: - return False - for decorator_attribute in node.decorators.nodes: - if isinstance(decorator_attribute, astroid.Call): # decorator with arguments - decorator_attribute = decorator_attribute.func - if decorator_attribute.as_string() in decorator_names: - return True - return False - - -def attr_attributes_transform(node): - """Given that the ClassNode has an attr decorator, - rewrite class attributes as instance attributes - """ - # Astroid can't infer this attribute properly - # Prevents https://github.com/PyCQA/pylint/issues/1884 - node.locals["__attrs_attrs__"] = [astroid.Unknown(parent=node)] - - for cdefbodynode in node.body: - if not isinstance(cdefbodynode, (astroid.Assign, astroid.AnnAssign)): - continue - if isinstance(cdefbodynode.value, astroid.Call): - if cdefbodynode.value.func.as_string() not in ATTRIB_NAMES: - continue - else: - continue - targets = ( - cdefbodynode.targets - if hasattr(cdefbodynode, "targets") - else [cdefbodynode.target] - ) - for target in targets: - - rhs_node = astroid.Unknown( - lineno=cdefbodynode.lineno, - col_offset=cdefbodynode.col_offset, - parent=cdefbodynode, - ) - node.locals[target.name] = [rhs_node] - node.instance_attrs[target.name] = [rhs_node] - - -MANAGER.register_transform( - astroid.ClassDef, attr_attributes_transform, is_decorated_with_attrs -) diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_boto3.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_boto3.py deleted file mode 100644 index 342ca57..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_boto3.py +++ /dev/null @@ -1,28 +0,0 @@ -# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html -# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER - -"""Astroid hooks for understanding boto3.ServiceRequest()""" -import astroid -from astroid import MANAGER, extract_node - -BOTO_SERVICE_FACTORY_QUALIFIED_NAME = "boto3.resources.base.ServiceResource" - - -def service_request_transform(node): - """Transform ServiceResource to look like dynamic classes""" - code = """ - def __getattr__(self, attr): - return 0 - """ - func_getattr = extract_node(code) - node.locals["__getattr__"] = [func_getattr] - return node - - -def _looks_like_boto3_service_request(node): - return node.qname() == BOTO_SERVICE_FACTORY_QUALIFIED_NAME - - -MANAGER.register_transform( - astroid.ClassDef, service_request_transform, _looks_like_boto3_service_request -) diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_builtin_inference.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_builtin_inference.py deleted file mode 100644 index 4b07ac5..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_builtin_inference.py +++ /dev/null @@ -1,873 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright (c) 2014-2020 Claudiu Popa -# Copyright (c) 2014-2015 LOGILAB S.A. (Paris, FRANCE) -# Copyright (c) 2015-2016 Ceridwen -# Copyright (c) 2015 Rene Zhang -# Copyright (c) 2018 Bryce Guinta -# Copyright (c) 2018 Ville Skyttä -# Copyright (c) 2019 Stanislav Levin -# Copyright (c) 2019 David Liu -# Copyright (c) 2019 Bryce Guinta -# Copyright (c) 2019 Frédéric Chapoton - -# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html -# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER - -"""Astroid hooks for various builtins.""" - -from functools import partial -from textwrap import dedent - -import six -from astroid import ( - MANAGER, - UseInferenceDefault, - AttributeInferenceError, - inference_tip, - InferenceError, - NameInferenceError, - AstroidTypeError, - MroError, -) -from astroid import arguments -from astroid.builder import AstroidBuilder -from astroid import helpers -from astroid import nodes -from astroid import objects -from astroid import scoped_nodes -from astroid import util - - -OBJECT_DUNDER_NEW = "object.__new__" - - -def _extend_str(class_node, rvalue): - """function to extend builtin str/unicode class""" - code = dedent( - """ - class whatever(object): - def join(self, iterable): - return {rvalue} - def replace(self, old, new, count=None): - return {rvalue} - def format(self, *args, **kwargs): - return {rvalue} - def encode(self, encoding='ascii', errors=None): - return '' - def decode(self, encoding='ascii', errors=None): - return u'' - def capitalize(self): - return {rvalue} - def title(self): - return {rvalue} - def lower(self): - return {rvalue} - def upper(self): - return {rvalue} - def swapcase(self): - return {rvalue} - def index(self, sub, start=None, end=None): - return 0 - def find(self, sub, start=None, end=None): - return 0 - def count(self, sub, start=None, end=None): - return 0 - def strip(self, chars=None): - return {rvalue} - def lstrip(self, chars=None): - return {rvalue} - def rstrip(self, chars=None): - return {rvalue} - def rjust(self, width, fillchar=None): - return {rvalue} - def center(self, width, fillchar=None): - return {rvalue} - def ljust(self, width, fillchar=None): - return {rvalue} - """ - ) - code = code.format(rvalue=rvalue) - fake = AstroidBuilder(MANAGER).string_build(code)["whatever"] - for method in fake.mymethods(): - method.parent = class_node - method.lineno = None - method.col_offset = None - if "__class__" in method.locals: - method.locals["__class__"] = [class_node] - class_node.locals[method.name] = [method] - method.parent = class_node - - -def _extend_builtins(class_transforms): - builtin_ast = MANAGER.builtins_module - for class_name, transform in class_transforms.items(): - transform(builtin_ast[class_name]) - - -_extend_builtins( - { - "bytes": partial(_extend_str, rvalue="b''"), - "str": partial(_extend_str, rvalue="''"), - } -) - - -def _builtin_filter_predicate(node, builtin_name): - if isinstance(node.func, nodes.Name) and node.func.name == builtin_name: - return True - if isinstance(node.func, nodes.Attribute): - return ( - node.func.attrname == "fromkeys" - and isinstance(node.func.expr, nodes.Name) - and node.func.expr.name == "dict" - ) - return False - - -def register_builtin_transform(transform, builtin_name): - """Register a new transform function for the given *builtin_name*. - - The transform function must accept two parameters, a node and - an optional context. - """ - - def _transform_wrapper(node, context=None): - result = transform(node, context=context) - if result: - if not result.parent: - # Let the transformation function determine - # the parent for its result. Otherwise, - # we set it to be the node we transformed from. - result.parent = node - - if result.lineno is None: - result.lineno = node.lineno - if result.col_offset is None: - result.col_offset = node.col_offset - return iter([result]) - - MANAGER.register_transform( - nodes.Call, - inference_tip(_transform_wrapper), - partial(_builtin_filter_predicate, builtin_name=builtin_name), - ) - - -def _container_generic_inference(node, context, node_type, transform): - args = node.args - if not args: - return node_type() - if len(node.args) > 1: - raise UseInferenceDefault() - - (arg,) = args - transformed = transform(arg) - if not transformed: - try: - inferred = next(arg.infer(context=context)) - except (InferenceError, StopIteration): - raise UseInferenceDefault() - if inferred is util.Uninferable: - raise UseInferenceDefault() - transformed = transform(inferred) - if not transformed or transformed is util.Uninferable: - raise UseInferenceDefault() - return transformed - - -def _container_generic_transform(arg, context, klass, iterables, build_elts): - if isinstance(arg, klass): - return arg - elif isinstance(arg, iterables): - if all(isinstance(elt, nodes.Const) for elt in arg.elts): - elts = [elt.value for elt in arg.elts] - else: - # TODO: Does not handle deduplication for sets. - elts = [] - for element in arg.elts: - inferred = helpers.safe_infer(element, context=context) - if inferred: - evaluated_object = nodes.EvaluatedObject( - original=element, value=inferred - ) - elts.append(evaluated_object) - elif isinstance(arg, nodes.Dict): - # Dicts need to have consts as strings already. - if not all(isinstance(elt[0], nodes.Const) for elt in arg.items): - raise UseInferenceDefault() - elts = [item[0].value for item in arg.items] - elif isinstance(arg, nodes.Const) and isinstance( - arg.value, (six.string_types, six.binary_type) - ): - elts = arg.value - else: - return - return klass.from_elements(elts=build_elts(elts)) - - -def _infer_builtin_container( - node, context, klass=None, iterables=None, build_elts=None -): - transform_func = partial( - _container_generic_transform, - context=context, - klass=klass, - iterables=iterables, - build_elts=build_elts, - ) - - return _container_generic_inference(node, context, klass, transform_func) - - -# pylint: disable=invalid-name -infer_tuple = partial( - _infer_builtin_container, - klass=nodes.Tuple, - iterables=( - nodes.List, - nodes.Set, - objects.FrozenSet, - objects.DictItems, - objects.DictKeys, - objects.DictValues, - ), - build_elts=tuple, -) - -infer_list = partial( - _infer_builtin_container, - klass=nodes.List, - iterables=( - nodes.Tuple, - nodes.Set, - objects.FrozenSet, - objects.DictItems, - objects.DictKeys, - objects.DictValues, - ), - build_elts=list, -) - -infer_set = partial( - _infer_builtin_container, - klass=nodes.Set, - iterables=(nodes.List, nodes.Tuple, objects.FrozenSet, objects.DictKeys), - build_elts=set, -) - -infer_frozenset = partial( - _infer_builtin_container, - klass=objects.FrozenSet, - iterables=(nodes.List, nodes.Tuple, nodes.Set, objects.FrozenSet, objects.DictKeys), - build_elts=frozenset, -) - - -def _get_elts(arg, context): - is_iterable = lambda n: isinstance(n, (nodes.List, nodes.Tuple, nodes.Set)) - try: - inferred = next(arg.infer(context)) - except (InferenceError, NameInferenceError): - raise UseInferenceDefault() - if isinstance(inferred, nodes.Dict): - items = inferred.items - elif is_iterable(inferred): - items = [] - for elt in inferred.elts: - # If an item is not a pair of two items, - # then fallback to the default inference. - # Also, take in consideration only hashable items, - # tuples and consts. We are choosing Names as well. - if not is_iterable(elt): - raise UseInferenceDefault() - if len(elt.elts) != 2: - raise UseInferenceDefault() - if not isinstance(elt.elts[0], (nodes.Tuple, nodes.Const, nodes.Name)): - raise UseInferenceDefault() - items.append(tuple(elt.elts)) - else: - raise UseInferenceDefault() - return items - - -def infer_dict(node, context=None): - """Try to infer a dict call to a Dict node. - - The function treats the following cases: - - * dict() - * dict(mapping) - * dict(iterable) - * dict(iterable, **kwargs) - * dict(mapping, **kwargs) - * dict(**kwargs) - - If a case can't be inferred, we'll fallback to default inference. - """ - call = arguments.CallSite.from_call(node, context=context) - if call.has_invalid_arguments() or call.has_invalid_keywords(): - raise UseInferenceDefault - - args = call.positional_arguments - kwargs = list(call.keyword_arguments.items()) - - if not args and not kwargs: - # dict() - return nodes.Dict() - elif kwargs and not args: - # dict(a=1, b=2, c=4) - items = [(nodes.Const(key), value) for key, value in kwargs] - elif len(args) == 1 and kwargs: - # dict(some_iterable, b=2, c=4) - elts = _get_elts(args[0], context) - keys = [(nodes.Const(key), value) for key, value in kwargs] - items = elts + keys - elif len(args) == 1: - items = _get_elts(args[0], context) - else: - raise UseInferenceDefault() - - value = nodes.Dict( - col_offset=node.col_offset, lineno=node.lineno, parent=node.parent - ) - value.postinit(items) - return value - - -def infer_super(node, context=None): - """Understand super calls. - - There are some restrictions for what can be understood: - - * unbounded super (one argument form) is not understood. - - * if the super call is not inside a function (classmethod or method), - then the default inference will be used. - - * if the super arguments can't be inferred, the default inference - will be used. - """ - if len(node.args) == 1: - # Ignore unbounded super. - raise UseInferenceDefault - - scope = node.scope() - if not isinstance(scope, nodes.FunctionDef): - # Ignore non-method uses of super. - raise UseInferenceDefault - if scope.type not in ("classmethod", "method"): - # Not interested in staticmethods. - raise UseInferenceDefault - - cls = scoped_nodes.get_wrapping_class(scope) - if not len(node.args): - mro_pointer = cls - # In we are in a classmethod, the interpreter will fill - # automatically the class as the second argument, not an instance. - if scope.type == "classmethod": - mro_type = cls - else: - mro_type = cls.instantiate_class() - else: - try: - mro_pointer = next(node.args[0].infer(context=context)) - except InferenceError: - raise UseInferenceDefault - try: - mro_type = next(node.args[1].infer(context=context)) - except InferenceError: - raise UseInferenceDefault - - if mro_pointer is util.Uninferable or mro_type is util.Uninferable: - # No way we could understand this. - raise UseInferenceDefault - - super_obj = objects.Super( - mro_pointer=mro_pointer, mro_type=mro_type, self_class=cls, scope=scope - ) - super_obj.parent = node - return super_obj - - -def _infer_getattr_args(node, context): - if len(node.args) not in (2, 3): - # Not a valid getattr call. - raise UseInferenceDefault - - try: - obj = next(node.args[0].infer(context=context)) - attr = next(node.args[1].infer(context=context)) - except InferenceError: - raise UseInferenceDefault - - if obj is util.Uninferable or attr is util.Uninferable: - # If one of the arguments is something we can't infer, - # then also make the result of the getattr call something - # which is unknown. - return util.Uninferable, util.Uninferable - - is_string = isinstance(attr, nodes.Const) and isinstance( - attr.value, six.string_types - ) - if not is_string: - raise UseInferenceDefault - - return obj, attr.value - - -def infer_getattr(node, context=None): - """Understand getattr calls - - If one of the arguments is an Uninferable object, then the - result will be an Uninferable object. Otherwise, the normal attribute - lookup will be done. - """ - obj, attr = _infer_getattr_args(node, context) - if ( - obj is util.Uninferable - or attr is util.Uninferable - or not hasattr(obj, "igetattr") - ): - return util.Uninferable - - try: - return next(obj.igetattr(attr, context=context)) - except (StopIteration, InferenceError, AttributeInferenceError): - if len(node.args) == 3: - # Try to infer the default and return it instead. - try: - return next(node.args[2].infer(context=context)) - except InferenceError: - raise UseInferenceDefault - - raise UseInferenceDefault - - -def infer_hasattr(node, context=None): - """Understand hasattr calls - - This always guarantees three possible outcomes for calling - hasattr: Const(False) when we are sure that the object - doesn't have the intended attribute, Const(True) when - we know that the object has the attribute and Uninferable - when we are unsure of the outcome of the function call. - """ - try: - obj, attr = _infer_getattr_args(node, context) - if ( - obj is util.Uninferable - or attr is util.Uninferable - or not hasattr(obj, "getattr") - ): - return util.Uninferable - obj.getattr(attr, context=context) - except UseInferenceDefault: - # Can't infer something from this function call. - return util.Uninferable - except AttributeInferenceError: - # Doesn't have it. - return nodes.Const(False) - return nodes.Const(True) - - -def infer_callable(node, context=None): - """Understand callable calls - - This follows Python's semantics, where an object - is callable if it provides an attribute __call__, - even though that attribute is something which can't be - called. - """ - if len(node.args) != 1: - # Invalid callable call. - raise UseInferenceDefault - - argument = node.args[0] - try: - inferred = next(argument.infer(context=context)) - except InferenceError: - return util.Uninferable - if inferred is util.Uninferable: - return util.Uninferable - return nodes.Const(inferred.callable()) - - -def infer_property(node, context=None): - """Understand `property` class - - This only infers the output of `property` - call, not the arguments themselves. - """ - if len(node.args) < 1: - # Invalid property call. - raise UseInferenceDefault - - getter = node.args[0] - try: - inferred = next(getter.infer(context=context)) - except InferenceError: - raise UseInferenceDefault - - if not isinstance(inferred, (nodes.FunctionDef, nodes.Lambda)): - raise UseInferenceDefault - - return objects.Property( - function=inferred, - name=inferred.name, - doc=getattr(inferred, "doc", None), - lineno=node.lineno, - parent=node, - col_offset=node.col_offset, - ) - - -def infer_bool(node, context=None): - """Understand bool calls.""" - if len(node.args) > 1: - # Invalid bool call. - raise UseInferenceDefault - - if not node.args: - return nodes.Const(False) - - argument = node.args[0] - try: - inferred = next(argument.infer(context=context)) - except InferenceError: - return util.Uninferable - if inferred is util.Uninferable: - return util.Uninferable - - bool_value = inferred.bool_value(context=context) - if bool_value is util.Uninferable: - return util.Uninferable - return nodes.Const(bool_value) - - -def infer_type(node, context=None): - """Understand the one-argument form of *type*.""" - if len(node.args) != 1: - raise UseInferenceDefault - - return helpers.object_type(node.args[0], context) - - -def infer_slice(node, context=None): - """Understand `slice` calls.""" - args = node.args - if not 0 < len(args) <= 3: - raise UseInferenceDefault - - infer_func = partial(helpers.safe_infer, context=context) - args = [infer_func(arg) for arg in args] - for arg in args: - if not arg or arg is util.Uninferable: - raise UseInferenceDefault - if not isinstance(arg, nodes.Const): - raise UseInferenceDefault - if not isinstance(arg.value, (type(None), int)): - raise UseInferenceDefault - - if len(args) < 3: - # Make sure we have 3 arguments. - args.extend([None] * (3 - len(args))) - - slice_node = nodes.Slice( - lineno=node.lineno, col_offset=node.col_offset, parent=node.parent - ) - slice_node.postinit(*args) - return slice_node - - -def _infer_object__new__decorator(node, context=None): - # Instantiate class immediately - # since that's what @object.__new__ does - return iter((node.instantiate_class(),)) - - -def _infer_object__new__decorator_check(node): - """Predicate before inference_tip - - Check if the given ClassDef has an @object.__new__ decorator - """ - if not node.decorators: - return False - - for decorator in node.decorators.nodes: - if isinstance(decorator, nodes.Attribute): - if decorator.as_string() == OBJECT_DUNDER_NEW: - return True - return False - - -def infer_issubclass(callnode, context=None): - """Infer issubclass() calls - - :param nodes.Call callnode: an `issubclass` call - :param InferenceContext: the context for the inference - :rtype nodes.Const: Boolean Const value of the `issubclass` call - :raises UseInferenceDefault: If the node cannot be inferred - """ - call = arguments.CallSite.from_call(callnode, context=context) - if call.keyword_arguments: - # issubclass doesn't support keyword arguments - raise UseInferenceDefault("TypeError: issubclass() takes no keyword arguments") - if len(call.positional_arguments) != 2: - raise UseInferenceDefault( - "Expected two arguments, got {count}".format( - count=len(call.positional_arguments) - ) - ) - # The left hand argument is the obj to be checked - obj_node, class_or_tuple_node = call.positional_arguments - - try: - obj_type = next(obj_node.infer(context=context)) - except InferenceError as exc: - raise UseInferenceDefault from exc - if not isinstance(obj_type, nodes.ClassDef): - raise UseInferenceDefault("TypeError: arg 1 must be class") - - # The right hand argument is the class(es) that the given - # object is to be checked against. - try: - class_container = _class_or_tuple_to_container( - class_or_tuple_node, context=context - ) - except InferenceError as exc: - raise UseInferenceDefault from exc - try: - issubclass_bool = helpers.object_issubclass(obj_type, class_container, context) - except AstroidTypeError as exc: - raise UseInferenceDefault("TypeError: " + str(exc)) from exc - except MroError as exc: - raise UseInferenceDefault from exc - return nodes.Const(issubclass_bool) - - -def infer_isinstance(callnode, context=None): - """Infer isinstance calls - - :param nodes.Call callnode: an isinstance call - :param InferenceContext: context for call - (currently unused but is a common interface for inference) - :rtype nodes.Const: Boolean Const value of isinstance call - - :raises UseInferenceDefault: If the node cannot be inferred - """ - call = arguments.CallSite.from_call(callnode, context=context) - if call.keyword_arguments: - # isinstance doesn't support keyword arguments - raise UseInferenceDefault("TypeError: isinstance() takes no keyword arguments") - if len(call.positional_arguments) != 2: - raise UseInferenceDefault( - "Expected two arguments, got {count}".format( - count=len(call.positional_arguments) - ) - ) - # The left hand argument is the obj to be checked - obj_node, class_or_tuple_node = call.positional_arguments - # The right hand argument is the class(es) that the given - # obj is to be check is an instance of - try: - class_container = _class_or_tuple_to_container( - class_or_tuple_node, context=context - ) - except InferenceError: - raise UseInferenceDefault - try: - isinstance_bool = helpers.object_isinstance(obj_node, class_container, context) - except AstroidTypeError as exc: - raise UseInferenceDefault("TypeError: " + str(exc)) - except MroError as exc: - raise UseInferenceDefault from exc - if isinstance_bool is util.Uninferable: - raise UseInferenceDefault - return nodes.Const(isinstance_bool) - - -def _class_or_tuple_to_container(node, context=None): - # Move inferences results into container - # to simplify later logic - # raises InferenceError if any of the inferences fall through - node_infer = next(node.infer(context=context)) - # arg2 MUST be a type or a TUPLE of types - # for isinstance - if isinstance(node_infer, nodes.Tuple): - class_container = [ - next(node.infer(context=context)) for node in node_infer.elts - ] - class_container = [ - klass_node for klass_node in class_container if klass_node is not None - ] - else: - class_container = [node_infer] - return class_container - - -def infer_len(node, context=None): - """Infer length calls - - :param nodes.Call node: len call to infer - :param context.InferenceContext: node context - :rtype nodes.Const: a Const node with the inferred length, if possible - """ - call = arguments.CallSite.from_call(node, context=context) - if call.keyword_arguments: - raise UseInferenceDefault("TypeError: len() must take no keyword arguments") - if len(call.positional_arguments) != 1: - raise UseInferenceDefault( - "TypeError: len() must take exactly one argument " - "({len}) given".format(len=len(call.positional_arguments)) - ) - [argument_node] = call.positional_arguments - try: - return nodes.Const(helpers.object_len(argument_node, context=context)) - except (AstroidTypeError, InferenceError) as exc: - raise UseInferenceDefault(str(exc)) from exc - - -def infer_str(node, context=None): - """Infer str() calls - - :param nodes.Call node: str() call to infer - :param context.InferenceContext: node context - :rtype nodes.Const: a Const containing an empty string - """ - call = arguments.CallSite.from_call(node, context=context) - if call.keyword_arguments: - raise UseInferenceDefault("TypeError: str() must take no keyword arguments") - try: - return nodes.Const("") - except (AstroidTypeError, InferenceError) as exc: - raise UseInferenceDefault(str(exc)) from exc - - -def infer_int(node, context=None): - """Infer int() calls - - :param nodes.Call node: int() call to infer - :param context.InferenceContext: node context - :rtype nodes.Const: a Const containing the integer value of the int() call - """ - call = arguments.CallSite.from_call(node, context=context) - if call.keyword_arguments: - raise UseInferenceDefault("TypeError: int() must take no keyword arguments") - - if call.positional_arguments: - try: - first_value = next(call.positional_arguments[0].infer(context=context)) - except (InferenceError, StopIteration) as exc: - raise UseInferenceDefault(str(exc)) from exc - - if first_value is util.Uninferable: - raise UseInferenceDefault - - if isinstance(first_value, nodes.Const) and isinstance( - first_value.value, (int, str) - ): - try: - actual_value = int(first_value.value) - except ValueError: - return nodes.Const(0) - return nodes.Const(actual_value) - - return nodes.Const(0) - - -def infer_dict_fromkeys(node, context=None): - """Infer dict.fromkeys - - :param nodes.Call node: dict.fromkeys() call to infer - :param context.InferenceContext: node context - :rtype nodes.Dict: - a Dictionary containing the values that astroid was able to infer. - In case the inference failed for any reason, an empty dictionary - will be inferred instead. - """ - - def _build_dict_with_elements(elements): - new_node = nodes.Dict( - col_offset=node.col_offset, lineno=node.lineno, parent=node.parent - ) - new_node.postinit(elements) - return new_node - - call = arguments.CallSite.from_call(node, context=context) - if call.keyword_arguments: - raise UseInferenceDefault("TypeError: int() must take no keyword arguments") - if len(call.positional_arguments) not in {1, 2}: - raise UseInferenceDefault( - "TypeError: Needs between 1 and 2 positional arguments" - ) - - default = nodes.Const(None) - values = call.positional_arguments[0] - try: - inferred_values = next(values.infer(context=context)) - except InferenceError: - return _build_dict_with_elements([]) - if inferred_values is util.Uninferable: - return _build_dict_with_elements([]) - - # Limit to a couple of potential values, as this can become pretty complicated - accepted_iterable_elements = (nodes.Const,) - if isinstance(inferred_values, (nodes.List, nodes.Set, nodes.Tuple)): - elements = inferred_values.elts - for element in elements: - if not isinstance(element, accepted_iterable_elements): - # Fallback to an empty dict - return _build_dict_with_elements([]) - - elements_with_value = [(element, default) for element in elements] - return _build_dict_with_elements(elements_with_value) - - elif isinstance(inferred_values, nodes.Const) and isinstance( - inferred_values.value, (str, bytes) - ): - elements = [ - (nodes.Const(element), default) for element in inferred_values.value - ] - return _build_dict_with_elements(elements) - elif isinstance(inferred_values, nodes.Dict): - keys = inferred_values.itered() - for key in keys: - if not isinstance(key, accepted_iterable_elements): - # Fallback to an empty dict - return _build_dict_with_elements([]) - - elements_with_value = [(element, default) for element in keys] - return _build_dict_with_elements(elements_with_value) - - # Fallback to an empty dictionary - return _build_dict_with_elements([]) - - -# Builtins inference -register_builtin_transform(infer_bool, "bool") -register_builtin_transform(infer_super, "super") -register_builtin_transform(infer_callable, "callable") -register_builtin_transform(infer_property, "property") -register_builtin_transform(infer_getattr, "getattr") -register_builtin_transform(infer_hasattr, "hasattr") -register_builtin_transform(infer_tuple, "tuple") -register_builtin_transform(infer_set, "set") -register_builtin_transform(infer_list, "list") -register_builtin_transform(infer_dict, "dict") -register_builtin_transform(infer_frozenset, "frozenset") -register_builtin_transform(infer_type, "type") -register_builtin_transform(infer_slice, "slice") -register_builtin_transform(infer_isinstance, "isinstance") -register_builtin_transform(infer_issubclass, "issubclass") -register_builtin_transform(infer_len, "len") -register_builtin_transform(infer_str, "str") -register_builtin_transform(infer_int, "int") -register_builtin_transform(infer_dict_fromkeys, "dict.fromkeys") - - -# Infer object.__new__ calls -MANAGER.register_transform( - nodes.ClassDef, - inference_tip(_infer_object__new__decorator), - _infer_object__new__decorator_check, -) diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_collections.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_collections.py deleted file mode 100644 index 669c6ca..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_collections.py +++ /dev/null @@ -1,75 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright (c) 2016, 2018 Claudiu Popa -# Copyright (c) 2016-2017 Łukasz Rogalski -# Copyright (c) 2017 Derek Gustafson -# Copyright (c) 2018 Ioana Tagirta -# Copyright (c) 2019 Hugo van Kemenade - -# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html -# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER -import sys - -import astroid - - -def _collections_transform(): - return astroid.parse( - """ - class defaultdict(dict): - default_factory = None - def __missing__(self, key): pass - def __getitem__(self, key): return default_factory - - """ - + _deque_mock() - + _ordered_dict_mock() - ) - - -def _deque_mock(): - base_deque_class = """ - class deque(object): - maxlen = 0 - def __init__(self, iterable=None, maxlen=None): - self.iterable = iterable or [] - def append(self, x): pass - def appendleft(self, x): pass - def clear(self): pass - def count(self, x): return 0 - def extend(self, iterable): pass - def extendleft(self, iterable): pass - def pop(self): return self.iterable[0] - def popleft(self): return self.iterable[0] - def remove(self, value): pass - def reverse(self): return reversed(self.iterable) - def rotate(self, n=1): return self - def __iter__(self): return self - def __reversed__(self): return self.iterable[::-1] - def __getitem__(self, index): return self.iterable[index] - def __setitem__(self, index, value): pass - def __delitem__(self, index): pass - def __bool__(self): return bool(self.iterable) - def __nonzero__(self): return bool(self.iterable) - def __contains__(self, o): return o in self.iterable - def __len__(self): return len(self.iterable) - def __copy__(self): return deque(self.iterable) - def copy(self): return deque(self.iterable) - def index(self, x, start=0, end=0): return 0 - def insert(self, x, i): pass - def __add__(self, other): pass - def __iadd__(self, other): pass - def __mul__(self, other): pass - def __imul__(self, other): pass - def __rmul__(self, other): pass""" - return base_deque_class - - -def _ordered_dict_mock(): - base_ordered_dict_class = """ - class OrderedDict(dict): - def __reversed__(self): return self[::-1] - def move_to_end(self, key, last=False): pass""" - return base_ordered_dict_class - - -astroid.register_module_extender(astroid.MANAGER, "collections", _collections_transform) diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_crypt.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_crypt.py deleted file mode 100644 index 491ee23..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_crypt.py +++ /dev/null @@ -1,26 +0,0 @@ -# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html -# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER -import sys -import astroid - -PY37 = sys.version_info >= (3, 7) - -if PY37: - # Since Python 3.7 Hashing Methods are added - # dynamically to globals() - - def _re_transform(): - return astroid.parse( - """ - from collections import namedtuple - _Method = namedtuple('_Method', 'name ident salt_chars total_size') - - METHOD_SHA512 = _Method('SHA512', '6', 16, 106) - METHOD_SHA256 = _Method('SHA256', '5', 16, 63) - METHOD_BLOWFISH = _Method('BLOWFISH', 2, 'b', 22) - METHOD_MD5 = _Method('MD5', '1', 8, 34) - METHOD_CRYPT = _Method('CRYPT', None, 2, 13) - """ - ) - - astroid.register_module_extender(astroid.MANAGER, "crypt", _re_transform) diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_curses.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_curses.py deleted file mode 100644 index 68e88b9..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_curses.py +++ /dev/null @@ -1,179 +0,0 @@ -# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html -# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER -import astroid - - -def _curses_transform(): - return astroid.parse( - """ - A_ALTCHARSET = 1 - A_BLINK = 1 - A_BOLD = 1 - A_DIM = 1 - A_INVIS = 1 - A_ITALIC = 1 - A_NORMAL = 1 - A_PROTECT = 1 - A_REVERSE = 1 - A_STANDOUT = 1 - A_UNDERLINE = 1 - A_HORIZONTAL = 1 - A_LEFT = 1 - A_LOW = 1 - A_RIGHT = 1 - A_TOP = 1 - A_VERTICAL = 1 - A_CHARTEXT = 1 - A_ATTRIBUTES = 1 - A_CHARTEXT = 1 - A_COLOR = 1 - KEY_MIN = 1 - KEY_BREAK = 1 - KEY_DOWN = 1 - KEY_UP = 1 - KEY_LEFT = 1 - KEY_RIGHT = 1 - KEY_HOME = 1 - KEY_BACKSPACE = 1 - KEY_F0 = 1 - KEY_Fn = 1 - KEY_DL = 1 - KEY_IL = 1 - KEY_DC = 1 - KEY_IC = 1 - KEY_EIC = 1 - KEY_CLEAR = 1 - KEY_EOS = 1 - KEY_EOL = 1 - KEY_SF = 1 - KEY_SR = 1 - KEY_NPAGE = 1 - KEY_PPAGE = 1 - KEY_STAB = 1 - KEY_CTAB = 1 - KEY_CATAB = 1 - KEY_ENTER = 1 - KEY_SRESET = 1 - KEY_RESET = 1 - KEY_PRINT = 1 - KEY_LL = 1 - KEY_A1 = 1 - KEY_A3 = 1 - KEY_B2 = 1 - KEY_C1 = 1 - KEY_C3 = 1 - KEY_BTAB = 1 - KEY_BEG = 1 - KEY_CANCEL = 1 - KEY_CLOSE = 1 - KEY_COMMAND = 1 - KEY_COPY = 1 - KEY_CREATE = 1 - KEY_END = 1 - KEY_EXIT = 1 - KEY_FIND = 1 - KEY_HELP = 1 - KEY_MARK = 1 - KEY_MESSAGE = 1 - KEY_MOVE = 1 - KEY_NEXT = 1 - KEY_OPEN = 1 - KEY_OPTIONS = 1 - KEY_PREVIOUS = 1 - KEY_REDO = 1 - KEY_REFERENCE = 1 - KEY_REFRESH = 1 - KEY_REPLACE = 1 - KEY_RESTART = 1 - KEY_RESUME = 1 - KEY_SAVE = 1 - KEY_SBEG = 1 - KEY_SCANCEL = 1 - KEY_SCOMMAND = 1 - KEY_SCOPY = 1 - KEY_SCREATE = 1 - KEY_SDC = 1 - KEY_SDL = 1 - KEY_SELECT = 1 - KEY_SEND = 1 - KEY_SEOL = 1 - KEY_SEXIT = 1 - KEY_SFIND = 1 - KEY_SHELP = 1 - KEY_SHOME = 1 - KEY_SIC = 1 - KEY_SLEFT = 1 - KEY_SMESSAGE = 1 - KEY_SMOVE = 1 - KEY_SNEXT = 1 - KEY_SOPTIONS = 1 - KEY_SPREVIOUS = 1 - KEY_SPRINT = 1 - KEY_SREDO = 1 - KEY_SREPLACE = 1 - KEY_SRIGHT = 1 - KEY_SRSUME = 1 - KEY_SSAVE = 1 - KEY_SSUSPEND = 1 - KEY_SUNDO = 1 - KEY_SUSPEND = 1 - KEY_UNDO = 1 - KEY_MOUSE = 1 - KEY_RESIZE = 1 - KEY_MAX = 1 - ACS_BBSS = 1 - ACS_BLOCK = 1 - ACS_BOARD = 1 - ACS_BSBS = 1 - ACS_BSSB = 1 - ACS_BSSS = 1 - ACS_BTEE = 1 - ACS_BULLET = 1 - ACS_CKBOARD = 1 - ACS_DARROW = 1 - ACS_DEGREE = 1 - ACS_DIAMOND = 1 - ACS_GEQUAL = 1 - ACS_HLINE = 1 - ACS_LANTERN = 1 - ACS_LARROW = 1 - ACS_LEQUAL = 1 - ACS_LLCORNER = 1 - ACS_LRCORNER = 1 - ACS_LTEE = 1 - ACS_NEQUAL = 1 - ACS_PI = 1 - ACS_PLMINUS = 1 - ACS_PLUS = 1 - ACS_RARROW = 1 - ACS_RTEE = 1 - ACS_S1 = 1 - ACS_S3 = 1 - ACS_S7 = 1 - ACS_S9 = 1 - ACS_SBBS = 1 - ACS_SBSB = 1 - ACS_SBSS = 1 - ACS_SSBB = 1 - ACS_SSBS = 1 - ACS_SSSB = 1 - ACS_SSSS = 1 - ACS_STERLING = 1 - ACS_TTEE = 1 - ACS_UARROW = 1 - ACS_ULCORNER = 1 - ACS_URCORNER = 1 - ACS_VLINE = 1 - COLOR_BLACK = 1 - COLOR_BLUE = 1 - COLOR_CYAN = 1 - COLOR_GREEN = 1 - COLOR_MAGENTA = 1 - COLOR_RED = 1 - COLOR_WHITE = 1 - COLOR_YELLOW = 1 - """ - ) - - -astroid.register_module_extender(astroid.MANAGER, "curses", _curses_transform) diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_dataclasses.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_dataclasses.py deleted file mode 100644 index 7a25e0c..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_dataclasses.py +++ /dev/null @@ -1,50 +0,0 @@ -# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html -# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER -""" -Astroid hook for the dataclasses library -""" - -import astroid -from astroid import MANAGER - - -DATACLASSES_DECORATORS = frozenset(("dataclasses.dataclass", "dataclass")) - - -def is_decorated_with_dataclass(node, decorator_names=DATACLASSES_DECORATORS): - """Return True if a decorated node has a `dataclass` decorator applied.""" - if not node.decorators: - return False - for decorator_attribute in node.decorators.nodes: - if isinstance(decorator_attribute, astroid.Call): # decorator with arguments - decorator_attribute = decorator_attribute.func - if decorator_attribute.as_string() in decorator_names: - return True - return False - - -def dataclass_transform(node): - """Rewrite a dataclass to be easily understood by pylint""" - - for assign_node in node.body: - if not isinstance(assign_node, (astroid.AnnAssign, astroid.Assign)): - continue - - targets = ( - assign_node.targets - if hasattr(assign_node, "targets") - else [assign_node.target] - ) - for target in targets: - rhs_node = astroid.Unknown( - lineno=assign_node.lineno, - col_offset=assign_node.col_offset, - parent=assign_node, - ) - node.instance_attrs[target.name] = [rhs_node] - node.locals[target.name] = [rhs_node] - - -MANAGER.register_transform( - astroid.ClassDef, dataclass_transform, is_decorated_with_dataclass -) diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_dateutil.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_dateutil.py deleted file mode 100644 index 9fdb9fd..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_dateutil.py +++ /dev/null @@ -1,28 +0,0 @@ -# Copyright (c) 2015-2016, 2018 Claudiu Popa -# Copyright (c) 2015 raylu -# Copyright (c) 2016 Ceridwen - -# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html -# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER - -"""Astroid hooks for dateutil""" - -import textwrap - -from astroid import MANAGER, register_module_extender -from astroid.builder import AstroidBuilder - - -def dateutil_transform(): - return AstroidBuilder(MANAGER).string_build( - textwrap.dedent( - """ - import datetime - def parse(timestr, parserinfo=None, **kwargs): - return datetime.datetime() - """ - ) - ) - - -register_module_extender(MANAGER, "dateutil.parser", dateutil_transform) diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_fstrings.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_fstrings.py deleted file mode 100644 index 298d58a..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_fstrings.py +++ /dev/null @@ -1,51 +0,0 @@ -# Copyright (c) 2017-2018 Claudiu Popa - -# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html -# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER -import collections -import sys - -import astroid - - -def _clone_node_with_lineno(node, parent, lineno): - cls = node.__class__ - other_fields = node._other_fields - _astroid_fields = node._astroid_fields - init_params = {"lineno": lineno, "col_offset": node.col_offset, "parent": parent} - postinit_params = {param: getattr(node, param) for param in _astroid_fields} - if other_fields: - init_params.update({param: getattr(node, param) for param in other_fields}) - new_node = cls(**init_params) - if hasattr(node, "postinit") and _astroid_fields: - for param, child in postinit_params.items(): - if child and not isinstance(child, collections.Sequence): - cloned_child = _clone_node_with_lineno( - node=child, lineno=new_node.lineno, parent=new_node - ) - postinit_params[param] = cloned_child - new_node.postinit(**postinit_params) - return new_node - - -def _transform_formatted_value(node): - if node.value and node.value.lineno == 1: - if node.lineno != node.value.lineno: - new_node = astroid.FormattedValue( - lineno=node.lineno, col_offset=node.col_offset, parent=node.parent - ) - new_value = _clone_node_with_lineno( - node=node.value, lineno=node.lineno, parent=new_node - ) - new_node.postinit(value=new_value, format_spec=node.format_spec) - return new_node - - -if sys.version_info[:2] >= (3, 6): - # TODO: this fix tries to *patch* http://bugs.python.org/issue29051 - # The problem is that FormattedValue.value, which is a Name node, - # has wrong line numbers, usually 1. This creates problems for pylint, - # which expects correct line numbers for things such as message control. - astroid.MANAGER.register_transform( - astroid.FormattedValue, _transform_formatted_value - ) diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_functools.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_functools.py deleted file mode 100644 index d6c6069..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_functools.py +++ /dev/null @@ -1,159 +0,0 @@ -# Copyright (c) 2016, 2018-2020 Claudiu Popa -# Copyright (c) 2018 hippo91 -# Copyright (c) 2018 Bryce Guinta - -"""Astroid hooks for understanding functools library module.""" -from functools import partial -from itertools import chain - -import astroid -from astroid import arguments -from astroid import BoundMethod -from astroid import extract_node -from astroid import helpers -from astroid.interpreter import objectmodel -from astroid import MANAGER -from astroid import objects - - -LRU_CACHE = "functools.lru_cache" - - -class LruWrappedModel(objectmodel.FunctionModel): - """Special attribute model for functions decorated with functools.lru_cache. - - The said decorators patches at decoration time some functions onto - the decorated function. - """ - - @property - def attr___wrapped__(self): - return self._instance - - @property - def attr_cache_info(self): - cache_info = extract_node( - """ - from functools import _CacheInfo - _CacheInfo(0, 0, 0, 0) - """ - ) - - class CacheInfoBoundMethod(BoundMethod): - def infer_call_result(self, caller, context=None): - yield helpers.safe_infer(cache_info) - - return CacheInfoBoundMethod(proxy=self._instance, bound=self._instance) - - @property - def attr_cache_clear(self): - node = extract_node("""def cache_clear(self): pass""") - return BoundMethod(proxy=node, bound=self._instance.parent.scope()) - - -def _transform_lru_cache(node, context=None): - # TODO: this is not ideal, since the node should be immutable, - # but due to https://github.com/PyCQA/astroid/issues/354, - # there's not much we can do now. - # Replacing the node would work partially, because, - # in pylint, the old node would still be available, leading - # to spurious false positives. - node.special_attributes = LruWrappedModel()(node) - return - - -def _functools_partial_inference(node, context=None): - call = arguments.CallSite.from_call(node, context=context) - number_of_positional = len(call.positional_arguments) - if number_of_positional < 1: - raise astroid.UseInferenceDefault( - "functools.partial takes at least one argument" - ) - if number_of_positional == 1 and not call.keyword_arguments: - raise astroid.UseInferenceDefault( - "functools.partial needs at least to have some filled arguments" - ) - - partial_function = call.positional_arguments[0] - try: - inferred_wrapped_function = next(partial_function.infer(context=context)) - except astroid.InferenceError as exc: - raise astroid.UseInferenceDefault from exc - if inferred_wrapped_function is astroid.Uninferable: - raise astroid.UseInferenceDefault("Cannot infer the wrapped function") - if not isinstance(inferred_wrapped_function, astroid.FunctionDef): - raise astroid.UseInferenceDefault("The wrapped function is not a function") - - # Determine if the passed keywords into the callsite are supported - # by the wrapped function. - function_parameters = chain( - inferred_wrapped_function.args.args or (), - inferred_wrapped_function.args.posonlyargs or (), - inferred_wrapped_function.args.kwonlyargs or (), - ) - parameter_names = set( - param.name - for param in function_parameters - if isinstance(param, astroid.AssignName) - ) - if set(call.keyword_arguments) - parameter_names: - raise astroid.UseInferenceDefault( - "wrapped function received unknown parameters" - ) - - partial_function = objects.PartialFunction( - call, - name=inferred_wrapped_function.name, - doc=inferred_wrapped_function.doc, - lineno=inferred_wrapped_function.lineno, - col_offset=inferred_wrapped_function.col_offset, - parent=inferred_wrapped_function.parent, - ) - partial_function.postinit( - args=inferred_wrapped_function.args, - body=inferred_wrapped_function.body, - decorators=inferred_wrapped_function.decorators, - returns=inferred_wrapped_function.returns, - type_comment_returns=inferred_wrapped_function.type_comment_returns, - type_comment_args=inferred_wrapped_function.type_comment_args, - ) - return iter((partial_function,)) - - -def _looks_like_lru_cache(node): - """Check if the given function node is decorated with lru_cache.""" - if not node.decorators: - return False - for decorator in node.decorators.nodes: - if not isinstance(decorator, astroid.Call): - continue - if _looks_like_functools_member(decorator, "lru_cache"): - return True - return False - - -def _looks_like_functools_member(node, member): - """Check if the given Call node is a functools.partial call""" - if isinstance(node.func, astroid.Name): - return node.func.name == member - elif isinstance(node.func, astroid.Attribute): - return ( - node.func.attrname == member - and isinstance(node.func.expr, astroid.Name) - and node.func.expr.name == "functools" - ) - - -_looks_like_partial = partial(_looks_like_functools_member, member="partial") - - -MANAGER.register_transform( - astroid.FunctionDef, _transform_lru_cache, _looks_like_lru_cache -) - - -MANAGER.register_transform( - astroid.Call, - astroid.inference_tip(_functools_partial_inference), - _looks_like_partial, -) diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_gi.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_gi.py deleted file mode 100644 index e49f3a2..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_gi.py +++ /dev/null @@ -1,253 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright (c) 2013-2014 LOGILAB S.A. (Paris, FRANCE) -# Copyright (c) 2014 Google, Inc. -# Copyright (c) 2014 Cole Robinson -# Copyright (c) 2015-2016, 2018 Claudiu Popa -# Copyright (c) 2015-2016 Ceridwen -# Copyright (c) 2015 David Shea -# Copyright (c) 2016 Jakub Wilk -# Copyright (c) 2016 Giuseppe Scrivano -# Copyright (c) 2018 Christoph Reiter -# Copyright (c) 2019 Philipp Hörist - -# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html -# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER - -"""Astroid hooks for the Python 2 GObject introspection bindings. - -Helps with understanding everything imported from 'gi.repository' -""" - -import inspect -import itertools -import sys -import re -import warnings - -from astroid import MANAGER, AstroidBuildingError, nodes -from astroid.builder import AstroidBuilder - - -_inspected_modules = {} - -_identifier_re = r"^[A-Za-z_]\w*$" - -_special_methods = frozenset( - { - "__lt__", - "__le__", - "__eq__", - "__ne__", - "__ge__", - "__gt__", - "__iter__", - "__getitem__", - "__setitem__", - "__delitem__", - "__len__", - "__bool__", - "__nonzero__", - "__next__", - "__str__", - "__len__", - "__contains__", - "__enter__", - "__exit__", - "__repr__", - "__getattr__", - "__setattr__", - "__delattr__", - "__del__", - "__hash__", - } -) - - -def _gi_build_stub(parent): - """ - Inspect the passed module recursively and build stubs for functions, - classes, etc. - """ - classes = {} - functions = {} - constants = {} - methods = {} - for name in dir(parent): - if name.startswith("__") and name not in _special_methods: - continue - - # Check if this is a valid name in python - if not re.match(_identifier_re, name): - continue - - try: - obj = getattr(parent, name) - except: - continue - - if inspect.isclass(obj): - classes[name] = obj - elif inspect.isfunction(obj) or inspect.isbuiltin(obj): - functions[name] = obj - elif inspect.ismethod(obj) or inspect.ismethoddescriptor(obj): - methods[name] = obj - elif ( - str(obj).startswith(", ) - # Only accept function calls with two constant arguments - if len(node.args) != 2: - return False - - if not all(isinstance(arg, nodes.Const) for arg in node.args): - return False - - func = node.func - if isinstance(func, nodes.Attribute): - if func.attrname != "require_version": - return False - if isinstance(func.expr, nodes.Name) and func.expr.name == "gi": - return True - - return False - - if isinstance(func, nodes.Name): - return func.name == "require_version" - - return False - - -def _register_require_version(node): - # Load the gi.require_version locally - try: - import gi - - gi.require_version(node.args[0].value, node.args[1].value) - except Exception: - pass - - return node - - -MANAGER.register_failed_import_hook(_import_gi_module) -MANAGER.register_transform( - nodes.Call, _register_require_version, _looks_like_require_version -) diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_hashlib.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_hashlib.py deleted file mode 100644 index eb34e15..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_hashlib.py +++ /dev/null @@ -1,69 +0,0 @@ -# Copyright (c) 2016, 2018 Claudiu Popa -# Copyright (c) 2018 David Poirier -# Copyright (c) 2018 wgehalo -# Copyright (c) 2018 Ioana Tagirta - -# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html -# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER -import sys - -import six - -import astroid - -PY36 = sys.version_info >= (3, 6) - - -def _hashlib_transform(): - signature = "value=''" - template = """ - class %(name)s(object): - def __init__(self, %(signature)s): pass - def digest(self): - return %(digest)s - def copy(self): - return self - def update(self, value): pass - def hexdigest(self): - return '' - @property - def name(self): - return %(name)r - @property - def block_size(self): - return 1 - @property - def digest_size(self): - return 1 - """ - algorithms_with_signature = dict.fromkeys( - ["md5", "sha1", "sha224", "sha256", "sha384", "sha512"], signature - ) - if PY36: - blake2b_signature = "data=b'', *, digest_size=64, key=b'', salt=b'', \ - person=b'', fanout=1, depth=1, leaf_size=0, node_offset=0, \ - node_depth=0, inner_size=0, last_node=False" - blake2s_signature = "data=b'', *, digest_size=32, key=b'', salt=b'', \ - person=b'', fanout=1, depth=1, leaf_size=0, node_offset=0, \ - node_depth=0, inner_size=0, last_node=False" - new_algorithms = dict.fromkeys( - ["sha3_224", "sha3_256", "sha3_384", "sha3_512", "shake_128", "shake_256"], - signature, - ) - algorithms_with_signature.update(new_algorithms) - algorithms_with_signature.update( - {"blake2b": blake2b_signature, "blake2s": blake2s_signature} - ) - classes = "".join( - template - % { - "name": hashfunc, - "digest": 'b""' if six.PY3 else '""', - "signature": signature, - } - for hashfunc, signature in algorithms_with_signature.items() - ) - return astroid.parse(classes) - - -astroid.register_module_extender(astroid.MANAGER, "hashlib", _hashlib_transform) diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_http.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_http.py deleted file mode 100644 index b16464e..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_http.py +++ /dev/null @@ -1,211 +0,0 @@ -# Copyright (c) 2018-2019 Claudiu Popa - -# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html -# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER - -"""Astroid brain hints for some of the `http` module.""" -import textwrap - -import astroid -from astroid.builder import AstroidBuilder - - -def _http_transform(): - code = textwrap.dedent( - """ - from collections import namedtuple - _HTTPStatus = namedtuple('_HTTPStatus', 'value phrase description') - - class HTTPStatus: - - @property - def phrase(self): - return "" - @property - def value(self): - return 0 - @property - def description(self): - return "" - - # informational - CONTINUE = _HTTPStatus(100, 'Continue', 'Request received, please continue') - SWITCHING_PROTOCOLS = _HTTPStatus(101, 'Switching Protocols', - 'Switching to new protocol; obey Upgrade header') - PROCESSING = _HTTPStatus(102, 'Processing', '') - OK = _HTTPStatus(200, 'OK', 'Request fulfilled, document follows') - CREATED = _HTTPStatus(201, 'Created', 'Document created, URL follows') - ACCEPTED = _HTTPStatus(202, 'Accepted', - 'Request accepted, processing continues off-line') - NON_AUTHORITATIVE_INFORMATION = _HTTPStatus(203, - 'Non-Authoritative Information', 'Request fulfilled from cache') - NO_CONTENT = _HTTPStatus(204, 'No Content', 'Request fulfilled, nothing follows') - RESET_CONTENT =_HTTPStatus(205, 'Reset Content', 'Clear input form for further input') - PARTIAL_CONTENT = _HTTPStatus(206, 'Partial Content', 'Partial content follows') - MULTI_STATUS = _HTTPStatus(207, 'Multi-Status', '') - ALREADY_REPORTED = _HTTPStatus(208, 'Already Reported', '') - IM_USED = _HTTPStatus(226, 'IM Used', '') - MULTIPLE_CHOICES = _HTTPStatus(300, 'Multiple Choices', - 'Object has several resources -- see URI list') - MOVED_PERMANENTLY = _HTTPStatus(301, 'Moved Permanently', - 'Object moved permanently -- see URI list') - FOUND = _HTTPStatus(302, 'Found', 'Object moved temporarily -- see URI list') - SEE_OTHER = _HTTPStatus(303, 'See Other', 'Object moved -- see Method and URL list') - NOT_MODIFIED = _HTTPStatus(304, 'Not Modified', - 'Document has not changed since given time') - USE_PROXY = _HTTPStatus(305, 'Use Proxy', - 'You must use proxy specified in Location to access this resource') - TEMPORARY_REDIRECT = _HTTPStatus(307, 'Temporary Redirect', - 'Object moved temporarily -- see URI list') - PERMANENT_REDIRECT = _HTTPStatus(308, 'Permanent Redirect', - 'Object moved permanently -- see URI list') - BAD_REQUEST = _HTTPStatus(400, 'Bad Request', - 'Bad request syntax or unsupported method') - UNAUTHORIZED = _HTTPStatus(401, 'Unauthorized', - 'No permission -- see authorization schemes') - PAYMENT_REQUIRED = _HTTPStatus(402, 'Payment Required', - 'No payment -- see charging schemes') - FORBIDDEN = _HTTPStatus(403, 'Forbidden', - 'Request forbidden -- authorization will not help') - NOT_FOUND = _HTTPStatus(404, 'Not Found', - 'Nothing matches the given URI') - METHOD_NOT_ALLOWED = _HTTPStatus(405, 'Method Not Allowed', - 'Specified method is invalid for this resource') - NOT_ACCEPTABLE = _HTTPStatus(406, 'Not Acceptable', - 'URI not available in preferred format') - PROXY_AUTHENTICATION_REQUIRED = _HTTPStatus(407, - 'Proxy Authentication Required', - 'You must authenticate with this proxy before proceeding') - REQUEST_TIMEOUT = _HTTPStatus(408, 'Request Timeout', - 'Request timed out; try again later') - CONFLICT = _HTTPStatus(409, 'Conflict', 'Request conflict') - GONE = _HTTPStatus(410, 'Gone', - 'URI no longer exists and has been permanently removed') - LENGTH_REQUIRED = _HTTPStatus(411, 'Length Required', - 'Client must specify Content-Length') - PRECONDITION_FAILED = _HTTPStatus(412, 'Precondition Failed', - 'Precondition in headers is false') - REQUEST_ENTITY_TOO_LARGE = _HTTPStatus(413, 'Request Entity Too Large', - 'Entity is too large') - REQUEST_URI_TOO_LONG = _HTTPStatus(414, 'Request-URI Too Long', - 'URI is too long') - UNSUPPORTED_MEDIA_TYPE = _HTTPStatus(415, 'Unsupported Media Type', - 'Entity body in unsupported format') - REQUESTED_RANGE_NOT_SATISFIABLE = _HTTPStatus(416, - 'Requested Range Not Satisfiable', - 'Cannot satisfy request range') - EXPECTATION_FAILED = _HTTPStatus(417, 'Expectation Failed', - 'Expect condition could not be satisfied') - MISDIRECTED_REQUEST = _HTTPStatus(421, 'Misdirected Request', - 'Server is not able to produce a response') - UNPROCESSABLE_ENTITY = _HTTPStatus(422, 'Unprocessable Entity') - LOCKED = _HTTPStatus(423, 'Locked') - FAILED_DEPENDENCY = _HTTPStatus(424, 'Failed Dependency') - UPGRADE_REQUIRED = _HTTPStatus(426, 'Upgrade Required') - PRECONDITION_REQUIRED = _HTTPStatus(428, 'Precondition Required', - 'The origin server requires the request to be conditional') - TOO_MANY_REQUESTS = _HTTPStatus(429, 'Too Many Requests', - 'The user has sent too many requests in ' - 'a given amount of time ("rate limiting")') - REQUEST_HEADER_FIELDS_TOO_LARGE = _HTTPStatus(431, - 'Request Header Fields Too Large', - 'The server is unwilling to process the request because its header ' - 'fields are too large') - UNAVAILABLE_FOR_LEGAL_REASONS = _HTTPStatus(451, - 'Unavailable For Legal Reasons', - 'The server is denying access to the ' - 'resource as a consequence of a legal demand') - INTERNAL_SERVER_ERROR = _HTTPStatus(500, 'Internal Server Error', - 'Server got itself in trouble') - NOT_IMPLEMENTED = _HTTPStatus(501, 'Not Implemented', - 'Server does not support this operation') - BAD_GATEWAY = _HTTPStatus(502, 'Bad Gateway', - 'Invalid responses from another server/proxy') - SERVICE_UNAVAILABLE = _HTTPStatus(503, 'Service Unavailable', - 'The server cannot process the request due to a high load') - GATEWAY_TIMEOUT = _HTTPStatus(504, 'Gateway Timeout', - 'The gateway server did not receive a timely response') - HTTP_VERSION_NOT_SUPPORTED = _HTTPStatus(505, 'HTTP Version Not Supported', - 'Cannot fulfill request') - VARIANT_ALSO_NEGOTIATES = _HTTPStatus(506, 'Variant Also Negotiates') - INSUFFICIENT_STORAGE = _HTTPStatus(507, 'Insufficient Storage') - LOOP_DETECTED = _HTTPStatus(508, 'Loop Detected') - NOT_EXTENDED = _HTTPStatus(510, 'Not Extended') - NETWORK_AUTHENTICATION_REQUIRED = _HTTPStatus(511, - 'Network Authentication Required', - 'The client needs to authenticate to gain network access') - """ - ) - return AstroidBuilder(astroid.MANAGER).string_build(code) - - -def _http_client_transform(): - return AstroidBuilder(astroid.MANAGER).string_build( - textwrap.dedent( - """ - from http import HTTPStatus - - CONTINUE = HTTPStatus.CONTINUE - SWITCHING_PROTOCOLS = HTTPStatus.SWITCHING_PROTOCOLS - PROCESSING = HTTPStatus.PROCESSING - OK = HTTPStatus.OK - CREATED = HTTPStatus.CREATED - ACCEPTED = HTTPStatus.ACCEPTED - NON_AUTHORITATIVE_INFORMATION = HTTPStatus.NON_AUTHORITATIVE_INFORMATION - NO_CONTENT = HTTPStatus.NO_CONTENT - RESET_CONTENT = HTTPStatus.RESET_CONTENT - PARTIAL_CONTENT = HTTPStatus.PARTIAL_CONTENT - MULTI_STATUS = HTTPStatus.MULTI_STATUS - ALREADY_REPORTED = HTTPStatus.ALREADY_REPORTED - IM_USED = HTTPStatus.IM_USED - MULTIPLE_CHOICES = HTTPStatus.MULTIPLE_CHOICES - MOVED_PERMANENTLY = HTTPStatus.MOVED_PERMANENTLY - FOUND = HTTPStatus.FOUND - SEE_OTHER = HTTPStatus.SEE_OTHER - NOT_MODIFIED = HTTPStatus.NOT_MODIFIED - USE_PROXY = HTTPStatus.USE_PROXY - TEMPORARY_REDIRECT = HTTPStatus.TEMPORARY_REDIRECT - PERMANENT_REDIRECT = HTTPStatus.PERMANENT_REDIRECT - BAD_REQUEST = HTTPStatus.BAD_REQUEST - UNAUTHORIZED = HTTPStatus.UNAUTHORIZED - PAYMENT_REQUIRED = HTTPStatus.PAYMENT_REQUIRED - FORBIDDEN = HTTPStatus.FORBIDDEN - NOT_FOUND = HTTPStatus.NOT_FOUND - METHOD_NOT_ALLOWED = HTTPStatus.METHOD_NOT_ALLOWED - NOT_ACCEPTABLE = HTTPStatus.NOT_ACCEPTABLE - PROXY_AUTHENTICATION_REQUIRED = HTTPStatus.PROXY_AUTHENTICATION_REQUIRED - REQUEST_TIMEOUT = HTTPStatus.REQUEST_TIMEOUT - CONFLICT = HTTPStatus.CONFLICT - GONE = HTTPStatus.GONE - LENGTH_REQUIRED = HTTPStatus.LENGTH_REQUIRED - PRECONDITION_FAILED = HTTPStatus.PRECONDITION_FAILED - REQUEST_ENTITY_TOO_LARGE = HTTPStatus.REQUEST_ENTITY_TOO_LARGE - REQUEST_URI_TOO_LONG = HTTPStatus.REQUEST_URI_TOO_LONG - UNSUPPORTED_MEDIA_TYPE = HTTPStatus.UNSUPPORTED_MEDIA_TYPE - REQUESTED_RANGE_NOT_SATISFIABLE = HTTPStatus.REQUESTED_RANGE_NOT_SATISFIABLE - EXPECTATION_FAILED = HTTPStatus.EXPECTATION_FAILED - UNPROCESSABLE_ENTITY = HTTPStatus.UNPROCESSABLE_ENTITY - LOCKED = HTTPStatus.LOCKED - FAILED_DEPENDENCY = HTTPStatus.FAILED_DEPENDENCY - UPGRADE_REQUIRED = HTTPStatus.UPGRADE_REQUIRED - PRECONDITION_REQUIRED = HTTPStatus.PRECONDITION_REQUIRED - TOO_MANY_REQUESTS = HTTPStatus.TOO_MANY_REQUESTS - REQUEST_HEADER_FIELDS_TOO_LARGE = HTTPStatus.REQUEST_HEADER_FIELDS_TOO_LARGE - INTERNAL_SERVER_ERROR = HTTPStatus.INTERNAL_SERVER_ERROR - NOT_IMPLEMENTED = HTTPStatus.NOT_IMPLEMENTED - BAD_GATEWAY = HTTPStatus.BAD_GATEWAY - SERVICE_UNAVAILABLE = HTTPStatus.SERVICE_UNAVAILABLE - GATEWAY_TIMEOUT = HTTPStatus.GATEWAY_TIMEOUT - HTTP_VERSION_NOT_SUPPORTED = HTTPStatus.HTTP_VERSION_NOT_SUPPORTED - VARIANT_ALSO_NEGOTIATES = HTTPStatus.VARIANT_ALSO_NEGOTIATES - INSUFFICIENT_STORAGE = HTTPStatus.INSUFFICIENT_STORAGE - LOOP_DETECTED = HTTPStatus.LOOP_DETECTED - NOT_EXTENDED = HTTPStatus.NOT_EXTENDED - NETWORK_AUTHENTICATION_REQUIRED = HTTPStatus.NETWORK_AUTHENTICATION_REQUIRED - """ - ) - ) - - -astroid.register_module_extender(astroid.MANAGER, "http", _http_transform) -astroid.register_module_extender(astroid.MANAGER, "http.client", _http_client_transform) diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_io.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_io.py deleted file mode 100644 index c745311..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_io.py +++ /dev/null @@ -1,45 +0,0 @@ -# Copyright (c) 2016, 2018 Claudiu Popa - -# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html -# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER - -"""Astroid brain hints for some of the _io C objects.""" - -import astroid - - -BUFFERED = {"BufferedWriter", "BufferedReader"} -TextIOWrapper = "TextIOWrapper" -FileIO = "FileIO" -BufferedWriter = "BufferedWriter" - - -def _generic_io_transform(node, name, cls): - """Transform the given name, by adding the given *class* as a member of the node.""" - - io_module = astroid.MANAGER.ast_from_module_name("_io") - attribute_object = io_module[cls] - instance = attribute_object.instantiate_class() - node.locals[name] = [instance] - - -def _transform_text_io_wrapper(node): - # This is not always correct, since it can vary with the type of the descriptor, - # being stdout, stderr or stdin. But we cannot get access to the name of the - # stream, which is why we are using the BufferedWriter class as a default - # value - return _generic_io_transform(node, name="buffer", cls=BufferedWriter) - - -def _transform_buffered(node): - return _generic_io_transform(node, name="raw", cls=FileIO) - - -astroid.MANAGER.register_transform( - astroid.ClassDef, _transform_buffered, lambda node: node.name in BUFFERED -) -astroid.MANAGER.register_transform( - astroid.ClassDef, - _transform_text_io_wrapper, - lambda node: node.name == TextIOWrapper, -) diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_mechanize.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_mechanize.py deleted file mode 100644 index ef62c53..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_mechanize.py +++ /dev/null @@ -1,29 +0,0 @@ -# Copyright (c) 2012-2013 LOGILAB S.A. (Paris, FRANCE) -# Copyright (c) 2014 Google, Inc. -# Copyright (c) 2015-2016, 2018 Claudiu Popa -# Copyright (c) 2016 Ceridwen - -# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html -# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER - -from astroid import MANAGER, register_module_extender -from astroid.builder import AstroidBuilder - - -def mechanize_transform(): - return AstroidBuilder(MANAGER).string_build( - """ - -class Browser(object): - def open(self, url, data=None, timeout=None): - return None - def open_novisit(self, url, data=None, timeout=None): - return None - def open_local_file(self, filename): - return None - -""" - ) - - -register_module_extender(MANAGER, "mechanize", mechanize_transform) diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_multiprocessing.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_multiprocessing.py deleted file mode 100644 index 3629b03..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_multiprocessing.py +++ /dev/null @@ -1,107 +0,0 @@ -# Copyright (c) 2016, 2018 Claudiu Popa -# Copyright (c) 2019 Hugo van Kemenade - -# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html -# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER - -import sys - -import astroid -from astroid import exceptions - - -def _multiprocessing_transform(): - module = astroid.parse( - """ - from multiprocessing.managers import SyncManager - def Manager(): - return SyncManager() - """ - ) - # Multiprocessing uses a getattr lookup inside contexts, - # in order to get the attributes they need. Since it's extremely - # dynamic, we use this approach to fake it. - node = astroid.parse( - """ - from multiprocessing.context import DefaultContext, BaseContext - default = DefaultContext() - base = BaseContext() - """ - ) - try: - context = next(node["default"].infer()) - base = next(node["base"].infer()) - except exceptions.InferenceError: - return module - - for node in (context, base): - for key, value in node.locals.items(): - if key.startswith("_"): - continue - - value = value[0] - if isinstance(value, astroid.FunctionDef): - # We need to rebound this, since otherwise - # it will have an extra argument (self). - value = astroid.BoundMethod(value, node) - module[key] = value - return module - - -def _multiprocessing_managers_transform(): - return astroid.parse( - """ - import array - import threading - import multiprocessing.pool as pool - - import six - - class Namespace(object): - pass - - class Value(object): - def __init__(self, typecode, value, lock=True): - self._typecode = typecode - self._value = value - def get(self): - return self._value - def set(self, value): - self._value = value - def __repr__(self): - return '%s(%r, %r)'%(type(self).__name__, self._typecode, self._value) - value = property(get, set) - - def Array(typecode, sequence, lock=True): - return array.array(typecode, sequence) - - class SyncManager(object): - Queue = JoinableQueue = six.moves.queue.Queue - Event = threading.Event - RLock = threading.RLock - BoundedSemaphore = threading.BoundedSemaphore - Condition = threading.Condition - Barrier = threading.Barrier - Pool = pool.Pool - list = list - dict = dict - Value = Value - Array = Array - Namespace = Namespace - __enter__ = lambda self: self - __exit__ = lambda *args: args - - def start(self, initializer=None, initargs=None): - pass - def shutdown(self): - pass - """ - ) - - -astroid.register_module_extender( - astroid.MANAGER, "multiprocessing.managers", _multiprocessing_managers_transform -) -astroid.register_module_extender( - astroid.MANAGER, "multiprocessing", _multiprocessing_transform -) diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_namedtuple_enum.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_namedtuple_enum.py deleted file mode 100644 index 13fcf79..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_namedtuple_enum.py +++ /dev/null @@ -1,455 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright (c) 2012-2015 LOGILAB S.A. (Paris, FRANCE) -# Copyright (c) 2013-2014 Google, Inc. -# Copyright (c) 2014-2020 Claudiu Popa -# Copyright (c) 2014 Eevee (Alex Munroe) -# Copyright (c) 2015-2016 Ceridwen -# Copyright (c) 2015 Dmitry Pribysh -# Copyright (c) 2015 David Shea -# Copyright (c) 2015 Philip Lorenz -# Copyright (c) 2016 Jakub Wilk -# Copyright (c) 2016 Mateusz Bysiek -# Copyright (c) 2017 Hugo -# Copyright (c) 2017 Łukasz Rogalski -# Copyright (c) 2018 Ville Skyttä -# Copyright (c) 2019 Ashley Whetter - -# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html -# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER - -"""Astroid hooks for the Python standard library.""" - -import functools -import keyword -from textwrap import dedent - -from astroid import MANAGER, UseInferenceDefault, inference_tip, InferenceError -from astroid import arguments -from astroid import exceptions -from astroid import nodes -from astroid.builder import AstroidBuilder, extract_node -from astroid import util - - -TYPING_NAMEDTUPLE_BASENAMES = {"NamedTuple", "typing.NamedTuple"} -ENUM_BASE_NAMES = { - "Enum", - "IntEnum", - "enum.Enum", - "enum.IntEnum", - "IntFlag", - "enum.IntFlag", -} - - -def _infer_first(node, context): - if node is util.Uninferable: - raise UseInferenceDefault - try: - value = next(node.infer(context=context)) - if value is util.Uninferable: - raise UseInferenceDefault() - else: - return value - except StopIteration: - raise InferenceError() - - -def _find_func_form_arguments(node, context): - def _extract_namedtuple_arg_or_keyword(position, key_name=None): - - if len(args) > position: - return _infer_first(args[position], context) - if key_name and key_name in found_keywords: - return _infer_first(found_keywords[key_name], context) - - args = node.args - keywords = node.keywords - found_keywords = ( - {keyword.arg: keyword.value for keyword in keywords} if keywords else {} - ) - - name = _extract_namedtuple_arg_or_keyword(position=0, key_name="typename") - names = _extract_namedtuple_arg_or_keyword(position=1, key_name="field_names") - if name and names: - return name.value, names - - raise UseInferenceDefault() - - -def infer_func_form(node, base_type, context=None, enum=False): - """Specific inference function for namedtuple or Python 3 enum. """ - # node is a Call node, class name as first argument and generated class - # attributes as second argument - - # namedtuple or enums list of attributes can be a list of strings or a - # whitespace-separate string - try: - name, names = _find_func_form_arguments(node, context) - try: - attributes = names.value.replace(",", " ").split() - except AttributeError: - if not enum: - attributes = [ - _infer_first(const, context).value for const in names.elts - ] - else: - # Enums supports either iterator of (name, value) pairs - # or mappings. - if hasattr(names, "items") and isinstance(names.items, list): - attributes = [ - _infer_first(const[0], context).value - for const in names.items - if isinstance(const[0], nodes.Const) - ] - elif hasattr(names, "elts"): - # Enums can support either ["a", "b", "c"] - # or [("a", 1), ("b", 2), ...], but they can't - # be mixed. - if all(isinstance(const, nodes.Tuple) for const in names.elts): - attributes = [ - _infer_first(const.elts[0], context).value - for const in names.elts - if isinstance(const, nodes.Tuple) - ] - else: - attributes = [ - _infer_first(const, context).value for const in names.elts - ] - else: - raise AttributeError - if not attributes: - raise AttributeError - except (AttributeError, exceptions.InferenceError): - raise UseInferenceDefault() - - attributes = [attr for attr in attributes if " " not in attr] - - # If we can't infer the name of the class, don't crash, up to this point - # we know it is a namedtuple anyway. - name = name or "Uninferable" - # we want to return a Class node instance with proper attributes set - class_node = nodes.ClassDef(name, "docstring") - class_node.parent = node.parent - # set base class=tuple - class_node.bases.append(base_type) - # XXX add __init__(*attributes) method - for attr in attributes: - fake_node = nodes.EmptyNode() - fake_node.parent = class_node - fake_node.attrname = attr - class_node.instance_attrs[attr] = [fake_node] - return class_node, name, attributes - - -def _has_namedtuple_base(node): - """Predicate for class inference tip - - :type node: ClassDef - :rtype: bool - """ - return set(node.basenames) & TYPING_NAMEDTUPLE_BASENAMES - - -def _looks_like(node, name): - func = node.func - if isinstance(func, nodes.Attribute): - return func.attrname == name - if isinstance(func, nodes.Name): - return func.name == name - return False - - -_looks_like_namedtuple = functools.partial(_looks_like, name="namedtuple") -_looks_like_enum = functools.partial(_looks_like, name="Enum") -_looks_like_typing_namedtuple = functools.partial(_looks_like, name="NamedTuple") - - -def infer_named_tuple(node, context=None): - """Specific inference function for namedtuple Call node""" - tuple_base_name = nodes.Name(name="tuple", parent=node.root()) - class_node, name, attributes = infer_func_form( - node, tuple_base_name, context=context - ) - call_site = arguments.CallSite.from_call(node, context=context) - func = next(extract_node("import collections; collections.namedtuple").infer()) - try: - rename = next(call_site.infer_argument(func, "rename", context)).bool_value() - except InferenceError: - rename = False - - if rename: - attributes = _get_renamed_namedtuple_attributes(attributes) - - replace_args = ", ".join("{arg}=None".format(arg=arg) for arg in attributes) - field_def = ( - " {name} = property(lambda self: self[{index:d}], " - "doc='Alias for field number {index:d}')" - ) - field_defs = "\n".join( - field_def.format(name=name, index=index) - for index, name in enumerate(attributes) - ) - fake = AstroidBuilder(MANAGER).string_build( - """ -class %(name)s(tuple): - __slots__ = () - _fields = %(fields)r - def _asdict(self): - return self.__dict__ - @classmethod - def _make(cls, iterable, new=tuple.__new__, len=len): - return new(cls, iterable) - def _replace(self, %(replace_args)s): - return self - def __getnewargs__(self): - return tuple(self) -%(field_defs)s - """ - % { - "name": name, - "fields": attributes, - "field_defs": field_defs, - "replace_args": replace_args, - } - ) - class_node.locals["_asdict"] = fake.body[0].locals["_asdict"] - class_node.locals["_make"] = fake.body[0].locals["_make"] - class_node.locals["_replace"] = fake.body[0].locals["_replace"] - class_node.locals["_fields"] = fake.body[0].locals["_fields"] - for attr in attributes: - class_node.locals[attr] = fake.body[0].locals[attr] - # we use UseInferenceDefault, we can't be a generator so return an iterator - return iter([class_node]) - - -def _get_renamed_namedtuple_attributes(field_names): - names = list(field_names) - seen = set() - for i, name in enumerate(field_names): - if ( - not all(c.isalnum() or c == "_" for c in name) - or keyword.iskeyword(name) - or not name - or name[0].isdigit() - or name.startswith("_") - or name in seen - ): - names[i] = "_%d" % i - seen.add(name) - return tuple(names) - - -def infer_enum(node, context=None): - """ Specific inference function for enum Call node. """ - enum_meta = extract_node( - """ - class EnumMeta(object): - 'docstring' - def __call__(self, node): - class EnumAttribute(object): - name = '' - value = 0 - return EnumAttribute() - def __iter__(self): - class EnumAttribute(object): - name = '' - value = 0 - return [EnumAttribute()] - def __reversed__(self): - class EnumAttribute(object): - name = '' - value = 0 - return (EnumAttribute, ) - def __next__(self): - return next(iter(self)) - def __getitem__(self, attr): - class Value(object): - @property - def name(self): - return '' - @property - def value(self): - return attr - - return Value() - __members__ = [''] - """ - ) - class_node = infer_func_form(node, enum_meta, context=context, enum=True)[0] - return iter([class_node.instantiate_class()]) - - -INT_FLAG_ADDITION_METHODS = """ - def __or__(self, other): - return {name}(self.value | other.value) - def __and__(self, other): - return {name}(self.value & other.value) - def __xor__(self, other): - return {name}(self.value ^ other.value) - def __add__(self, other): - return {name}(self.value + other.value) - def __div__(self, other): - return {name}(self.value / other.value) - def __invert__(self): - return {name}(~self.value) - def __mul__(self, other): - return {name}(self.value * other.value) -""" - - -def infer_enum_class(node): - """ Specific inference for enums. """ - for basename in node.basenames: - # TODO: doesn't handle subclasses yet. This implementation - # is a hack to support enums. - if basename not in ENUM_BASE_NAMES: - continue - if node.root().name == "enum": - # Skip if the class is directly from enum module. - break - for local, values in node.locals.items(): - if any(not isinstance(value, nodes.AssignName) for value in values): - continue - - targets = [] - stmt = values[0].statement() - if isinstance(stmt, nodes.Assign): - if isinstance(stmt.targets[0], nodes.Tuple): - targets = stmt.targets[0].itered() - else: - targets = stmt.targets - elif isinstance(stmt, nodes.AnnAssign): - targets = [stmt.target] - else: - continue - - inferred_return_value = None - if isinstance(stmt, nodes.Assign): - if isinstance(stmt.value, nodes.Const): - if isinstance(stmt.value.value, str): - inferred_return_value = repr(stmt.value.value) - else: - inferred_return_value = stmt.value.value - else: - inferred_return_value = stmt.value.as_string() - - new_targets = [] - for target in targets: - # Replace all the assignments with our mocked class. - classdef = dedent( - """ - class {name}({types}): - @property - def value(self): - return {return_value} - @property - def name(self): - return "{name}" - """.format( - name=target.name, - types=", ".join(node.basenames), - return_value=inferred_return_value, - ) - ) - if "IntFlag" in basename: - # Alright, we need to add some additional methods. - # Unfortunately we still can't infer the resulting objects as - # Enum members, but once we'll be able to do that, the following - # should result in some nice symbolic execution - classdef += INT_FLAG_ADDITION_METHODS.format(name=target.name) - - fake = AstroidBuilder(MANAGER).string_build(classdef)[target.name] - fake.parent = target.parent - for method in node.mymethods(): - fake.locals[method.name] = [method] - new_targets.append(fake.instantiate_class()) - node.locals[local] = new_targets - break - return node - - -def infer_typing_namedtuple_class(class_node, context=None): - """Infer a subclass of typing.NamedTuple""" - # Check if it has the corresponding bases - annassigns_fields = [ - annassign.target.name - for annassign in class_node.body - if isinstance(annassign, nodes.AnnAssign) - ] - code = dedent( - """ - from collections import namedtuple - namedtuple({typename!r}, {fields!r}) - """ - ).format(typename=class_node.name, fields=",".join(annassigns_fields)) - node = extract_node(code) - generated_class_node = next(infer_named_tuple(node, context)) - for method in class_node.mymethods(): - generated_class_node.locals[method.name] = [method] - - for assign in class_node.body: - if not isinstance(assign, nodes.Assign): - continue - - for target in assign.targets: - attr = target.name - generated_class_node.locals[attr] = class_node.locals[attr] - - return iter((generated_class_node,)) - - -def infer_typing_namedtuple(node, context=None): - """Infer a typing.NamedTuple(...) call.""" - # This is essentially a namedtuple with different arguments - # so we extract the args and infer a named tuple. - try: - func = next(node.func.infer()) - except InferenceError: - raise UseInferenceDefault - - if func.qname() != "typing.NamedTuple": - raise UseInferenceDefault - - if len(node.args) != 2: - raise UseInferenceDefault - - if not isinstance(node.args[1], (nodes.List, nodes.Tuple)): - raise UseInferenceDefault - - names = [] - for elt in node.args[1].elts: - if not isinstance(elt, (nodes.List, nodes.Tuple)): - raise UseInferenceDefault - if len(elt.elts) != 2: - raise UseInferenceDefault - names.append(elt.elts[0].as_string()) - - typename = node.args[0].as_string() - if names: - field_names = "({},)".format(",".join(names)) - else: - field_names = "''" - node = extract_node( - "namedtuple({typename}, {fields})".format(typename=typename, fields=field_names) - ) - return infer_named_tuple(node, context) - - -MANAGER.register_transform( - nodes.Call, inference_tip(infer_named_tuple), _looks_like_namedtuple -) -MANAGER.register_transform(nodes.Call, inference_tip(infer_enum), _looks_like_enum) -MANAGER.register_transform( - nodes.ClassDef, - infer_enum_class, - predicate=lambda cls: any( - basename for basename in cls.basenames if basename in ENUM_BASE_NAMES - ), -) -MANAGER.register_transform( - nodes.ClassDef, inference_tip(infer_typing_namedtuple_class), _has_namedtuple_base -) -MANAGER.register_transform( - nodes.Call, inference_tip(infer_typing_namedtuple), _looks_like_typing_namedtuple -) diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_nose.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_nose.py deleted file mode 100644 index d0280a3..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_nose.py +++ /dev/null @@ -1,77 +0,0 @@ -# Copyright (c) 2015-2016, 2018 Claudiu Popa -# Copyright (c) 2016 Ceridwen - -# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html -# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER - - -"""Hooks for nose library.""" - -import re -import textwrap - -import astroid -import astroid.builder - -_BUILDER = astroid.builder.AstroidBuilder(astroid.MANAGER) - - -def _pep8(name, caps=re.compile("([A-Z])")): - return caps.sub(lambda m: "_" + m.groups()[0].lower(), name) - - -def _nose_tools_functions(): - """Get an iterator of names and bound methods.""" - module = _BUILDER.string_build( - textwrap.dedent( - """ - import unittest - - class Test(unittest.TestCase): - pass - a = Test() - """ - ) - ) - try: - case = next(module["a"].infer()) - except astroid.InferenceError: - return - for method in case.methods(): - if method.name.startswith("assert") and "_" not in method.name: - pep8_name = _pep8(method.name) - yield pep8_name, astroid.BoundMethod(method, case) - if method.name == "assertEqual": - # nose also exports assert_equals. - yield "assert_equals", astroid.BoundMethod(method, case) - - -def _nose_tools_transform(node): - for method_name, method in _nose_tools_functions(): - node.locals[method_name] = [method] - - -def _nose_tools_trivial_transform(): - """Custom transform for the nose.tools module.""" - stub = _BUILDER.string_build("""__all__ = []""") - all_entries = ["ok_", "eq_"] - - for pep8_name, method in _nose_tools_functions(): - all_entries.append(pep8_name) - stub[pep8_name] = method - - # Update the __all__ variable, since nose.tools - # does this manually with .append. - all_assign = stub["__all__"].parent - all_object = astroid.List(all_entries) - all_object.parent = all_assign - all_assign.value = all_object - return stub - - -astroid.register_module_extender( - astroid.MANAGER, "nose.tools.trivial", _nose_tools_trivial_transform -) -astroid.MANAGER.register_transform( - astroid.Module, _nose_tools_transform, lambda n: n.name == "nose.tools" -) diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_numpy_core_fromnumeric.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_numpy_core_fromnumeric.py deleted file mode 100644 index 62dfe99..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_numpy_core_fromnumeric.py +++ /dev/null @@ -1,23 +0,0 @@ -# Copyright (c) 2019 hippo91 - -# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html -# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER - - -"""Astroid hooks for numpy.core.fromnumeric module.""" - -import astroid - - -def numpy_core_fromnumeric_transform(): - return astroid.parse( - """ - def sum(a, axis=None, dtype=None, out=None, keepdims=None, initial=None): - return numpy.ndarray([0, 0]) - """ - ) - - -astroid.register_module_extender( - astroid.MANAGER, "numpy.core.fromnumeric", numpy_core_fromnumeric_transform -) diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_numpy_core_function_base.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_numpy_core_function_base.py deleted file mode 100644 index 58aa0a9..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_numpy_core_function_base.py +++ /dev/null @@ -1,29 +0,0 @@ -# Copyright (c) 2019 hippo91 - -# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html -# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER - - -"""Astroid hooks for numpy.core.function_base module.""" - -import functools -import astroid -from brain_numpy_utils import looks_like_numpy_member, infer_numpy_member - - -METHODS_TO_BE_INFERRED = { - "linspace": """def linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0): - return numpy.ndarray([0, 0])""", - "logspace": """def logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None, axis=0): - return numpy.ndarray([0, 0])""", - "geomspace": """def geomspace(start, stop, num=50, endpoint=True, dtype=None, axis=0): - return numpy.ndarray([0, 0])""", -} - -for func_name, func_src in METHODS_TO_BE_INFERRED.items(): - inference_function = functools.partial(infer_numpy_member, func_src) - astroid.MANAGER.register_transform( - astroid.Attribute, - astroid.inference_tip(inference_function), - functools.partial(looks_like_numpy_member, func_name), - ) diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_numpy_core_multiarray.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_numpy_core_multiarray.py deleted file mode 100644 index b2e32bc..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_numpy_core_multiarray.py +++ /dev/null @@ -1,92 +0,0 @@ -# Copyright (c) 2019-2020 hippo91 - -# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html -# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER - - -"""Astroid hooks for numpy.core.multiarray module.""" - -import functools -import astroid -from brain_numpy_utils import looks_like_numpy_member, infer_numpy_member - - -def numpy_core_multiarray_transform(): - return astroid.parse( - """ - # different functions defined in multiarray.py - def inner(a, b): - return numpy.ndarray([0, 0]) - - def vdot(a, b): - return numpy.ndarray([0, 0]) - """ - ) - - -astroid.register_module_extender( - astroid.MANAGER, "numpy.core.multiarray", numpy_core_multiarray_transform -) - - -METHODS_TO_BE_INFERRED = { - "array": """def array(object, dtype=None, copy=True, order='K', subok=False, ndmin=0): - return numpy.ndarray([0, 0])""", - "dot": """def dot(a, b, out=None): - return numpy.ndarray([0, 0])""", - "empty_like": """def empty_like(a, dtype=None, order='K', subok=True): - return numpy.ndarray((0, 0))""", - "concatenate": """def concatenate(arrays, axis=None, out=None): - return numpy.ndarray((0, 0))""", - "where": """def where(condition, x=None, y=None): - return numpy.ndarray([0, 0])""", - "empty": """def empty(shape, dtype=float, order='C'): - return numpy.ndarray([0, 0])""", - "bincount": """def bincount(x, weights=None, minlength=0): - return numpy.ndarray([0, 0])""", - "busday_count": """def busday_count(begindates, enddates, weekmask='1111100', holidays=[], busdaycal=None, out=None): - return numpy.ndarray([0, 0])""", - "busday_offset": """def busday_offset(dates, offsets, roll='raise', weekmask='1111100', holidays=None, busdaycal=None, out=None): - return numpy.ndarray([0, 0])""", - "can_cast": """def can_cast(from_, to, casting='safe'): - return True""", - "copyto": """def copyto(dst, src, casting='same_kind', where=True): - return None""", - "datetime_as_string": """def datetime_as_string(arr, unit=None, timezone='naive', casting='same_kind'): - return numpy.ndarray([0, 0])""", - "is_busday": """def is_busday(dates, weekmask='1111100', holidays=None, busdaycal=None, out=None): - return numpy.ndarray([0, 0])""", - "lexsort": """def lexsort(keys, axis=-1): - return numpy.ndarray([0, 0])""", - "may_share_memory": """def may_share_memory(a, b, max_work=None): - return True""", - # Not yet available because dtype is not yet present in those brains - # "min_scalar_type": """def min_scalar_type(a): - # return numpy.dtype('int16')""", - "packbits": """def packbits(a, axis=None, bitorder='big'): - return numpy.ndarray([0, 0])""", - # Not yet available because dtype is not yet present in those brains - # "result_type": """def result_type(*arrays_and_dtypes): - # return numpy.dtype('int16')""", - "shares_memory": """def shares_memory(a, b, max_work=None): - return True""", - "unpackbits": """def unpackbits(a, axis=None, count=None, bitorder='big'): - return numpy.ndarray([0, 0])""", - "unravel_index": """def unravel_index(indices, shape, order='C'): - return (numpy.ndarray([0, 0]),)""", - "zeros": """def zeros(shape, dtype=float, order='C'): - return numpy.ndarray([0, 0])""", -} - -for method_name, function_src in METHODS_TO_BE_INFERRED.items(): - inference_function = functools.partial(infer_numpy_member, function_src) - astroid.MANAGER.register_transform( - astroid.Attribute, - astroid.inference_tip(inference_function), - functools.partial(looks_like_numpy_member, method_name), - ) - astroid.MANAGER.register_transform( - astroid.Name, - astroid.inference_tip(inference_function), - functools.partial(looks_like_numpy_member, method_name), - ) diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_numpy_core_numeric.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_numpy_core_numeric.py deleted file mode 100644 index 2a6f37e..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_numpy_core_numeric.py +++ /dev/null @@ -1,43 +0,0 @@ -# Copyright (c) 2019 hippo91 - -# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html -# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER - - -"""Astroid hooks for numpy.core.numeric module.""" - -import functools -import astroid -from brain_numpy_utils import looks_like_numpy_member, infer_numpy_member - - -def numpy_core_numeric_transform(): - return astroid.parse( - """ - # different functions defined in numeric.py - import numpy - def zeros_like(a, dtype=None, order='K', subok=True): return numpy.ndarray((0, 0)) - def ones_like(a, dtype=None, order='K', subok=True): return numpy.ndarray((0, 0)) - def full_like(a, fill_value, dtype=None, order='K', subok=True): return numpy.ndarray((0, 0)) - """ - ) - - -astroid.register_module_extender( - astroid.MANAGER, "numpy.core.numeric", numpy_core_numeric_transform -) - - -METHODS_TO_BE_INFERRED = { - "ones": """def ones(shape, dtype=None, order='C'): - return numpy.ndarray([0, 0])""" -} - - -for method_name, function_src in METHODS_TO_BE_INFERRED.items(): - inference_function = functools.partial(infer_numpy_member, function_src) - astroid.MANAGER.register_transform( - astroid.Attribute, - astroid.inference_tip(inference_function), - functools.partial(looks_like_numpy_member, method_name), - ) diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_numpy_core_numerictypes.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_numpy_core_numerictypes.py deleted file mode 100644 index 6ac4a14..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_numpy_core_numerictypes.py +++ /dev/null @@ -1,254 +0,0 @@ -# Copyright (c) 2019-2020 hippo91 - -# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html -# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER - -# TODO(hippo91) : correct the methods signature. - -"""Astroid hooks for numpy.core.numerictypes module.""" - -import astroid - - -def numpy_core_numerictypes_transform(): - # TODO: Uniformize the generic API with the ndarray one. - # According to numpy doc the generic object should expose - # the same API than ndarray. This has been done here partially - # through the astype method. - return astroid.parse( - """ - # different types defined in numerictypes.py - class generic(object): - def __init__(self, value): - self.T = None - self.base = None - self.data = None - self.dtype = None - self.flags = None - self.flat = None - self.imag = None - self.itemsize = None - self.nbytes = None - self.ndim = None - self.real = None - self.size = None - self.strides = None - - def all(self): return uninferable - def any(self): return uninferable - def argmax(self): return uninferable - def argmin(self): return uninferable - def argsort(self): return uninferable - def astype(self, dtype, order='K', casting='unsafe', subok=True, copy=True): return np.ndarray([0, 0]) - def base(self): return uninferable - def byteswap(self): return uninferable - def choose(self): return uninferable - def clip(self): return uninferable - def compress(self): return uninferable - def conj(self): return uninferable - def conjugate(self): return uninferable - def copy(self): return uninferable - def cumprod(self): return uninferable - def cumsum(self): return uninferable - def data(self): return uninferable - def diagonal(self): return uninferable - def dtype(self): return uninferable - def dump(self): return uninferable - def dumps(self): return uninferable - def fill(self): return uninferable - def flags(self): return uninferable - def flat(self): return uninferable - def flatten(self): return uninferable - def getfield(self): return uninferable - def imag(self): return uninferable - def item(self): return uninferable - def itemset(self): return uninferable - def itemsize(self): return uninferable - def max(self): return uninferable - def mean(self): return uninferable - def min(self): return uninferable - def nbytes(self): return uninferable - def ndim(self): return uninferable - def newbyteorder(self): return uninferable - def nonzero(self): return uninferable - def prod(self): return uninferable - def ptp(self): return uninferable - def put(self): return uninferable - def ravel(self): return uninferable - def real(self): return uninferable - def repeat(self): return uninferable - def reshape(self): return uninferable - def resize(self): return uninferable - def round(self): return uninferable - def searchsorted(self): return uninferable - def setfield(self): return uninferable - def setflags(self): return uninferable - def shape(self): return uninferable - def size(self): return uninferable - def sort(self): return uninferable - def squeeze(self): return uninferable - def std(self): return uninferable - def strides(self): return uninferable - def sum(self): return uninferable - def swapaxes(self): return uninferable - def take(self): return uninferable - def tobytes(self): return uninferable - def tofile(self): return uninferable - def tolist(self): return uninferable - def tostring(self): return uninferable - def trace(self): return uninferable - def transpose(self): return uninferable - def var(self): return uninferable - def view(self): return uninferable - - - class dtype(object): - def __init__(self, obj, align=False, copy=False): - self.alignment = None - self.base = None - self.byteorder = None - self.char = None - self.descr = None - self.fields = None - self.flags = None - self.hasobject = None - self.isalignedstruct = None - self.isbuiltin = None - self.isnative = None - self.itemsize = None - self.kind = None - self.metadata = None - self.name = None - self.names = None - self.num = None - self.shape = None - self.str = None - self.subdtype = None - self.type = None - - def newbyteorder(self, new_order='S'): return uninferable - def __neg__(self): return uninferable - - class busdaycalendar(object): - def __init__(self, weekmask='1111100', holidays=None): - self.holidays = None - self.weekmask = None - - class flexible(generic): pass - class bool_(generic): pass - class number(generic): - def __neg__(self): return uninferable - class datetime64(generic): - def __init__(self, nb, unit=None): pass - - - class void(flexible): - def __init__(self, *args, **kwargs): - self.base = None - self.dtype = None - self.flags = None - def getfield(self): return uninferable - def setfield(self): return uninferable - - - class character(flexible): pass - - - class integer(number): - def __init__(self, value): - self.denominator = None - self.numerator = None - - - class inexact(number): pass - - - class str_(str, character): - def maketrans(self, x, y=None, z=None): return uninferable - - - class bytes_(bytes, character): - def fromhex(self, string): return uninferable - def maketrans(self, frm, to): return uninferable - - - class signedinteger(integer): pass - - - class unsignedinteger(integer): pass - - - class complexfloating(inexact): pass - - - class floating(inexact): pass - - - class float64(floating, float): - def fromhex(self, string): return uninferable - - - class uint64(unsignedinteger): pass - class complex64(complexfloating): pass - class int16(signedinteger): pass - class float96(floating): pass - class int8(signedinteger): pass - class uint32(unsignedinteger): pass - class uint8(unsignedinteger): pass - class _typedict(dict): pass - class complex192(complexfloating): pass - class timedelta64(signedinteger): - def __init__(self, nb, unit=None): pass - class int32(signedinteger): pass - class uint16(unsignedinteger): pass - class float32(floating): pass - class complex128(complexfloating, complex): pass - class float16(floating): pass - class int64(signedinteger): pass - - buffer_type = memoryview - bool8 = bool_ - byte = int8 - bytes0 = bytes_ - cdouble = complex128 - cfloat = complex128 - clongdouble = complex192 - clongfloat = complex192 - complex_ = complex128 - csingle = complex64 - double = float64 - float_ = float64 - half = float16 - int0 = int32 - int_ = int32 - intc = int32 - intp = int32 - long = int32 - longcomplex = complex192 - longdouble = float96 - longfloat = float96 - longlong = int64 - object0 = object_ - object_ = object_ - short = int16 - single = float32 - singlecomplex = complex64 - str0 = str_ - string_ = bytes_ - ubyte = uint8 - uint = uint32 - uint0 = uint32 - uintc = uint32 - uintp = uint32 - ulonglong = uint64 - unicode = str_ - unicode_ = str_ - ushort = uint16 - void0 = void - """ - ) - - -astroid.register_module_extender( - astroid.MANAGER, "numpy.core.numerictypes", numpy_core_numerictypes_transform -) diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_numpy_core_umath.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_numpy_core_umath.py deleted file mode 100644 index 897961e..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_numpy_core_umath.py +++ /dev/null @@ -1,147 +0,0 @@ -# Copyright (c) 2019 hippo91 - -# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html -# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER - - -"""Astroid hooks for numpy.core.umath module.""" - -import astroid - - -def numpy_core_umath_transform(): - ufunc_optional_keyword_arguments = ( - """out=None, where=True, casting='same_kind', order='K', """ - """dtype=None, subok=True""" - ) - return astroid.parse( - """ - class FakeUfunc: - def __init__(self): - self.__doc__ = str() - self.__name__ = str() - self.nin = 0 - self.nout = 0 - self.nargs = 0 - self.ntypes = 0 - self.types = None - self.identity = None - self.signature = None - - @classmethod - def reduce(cls, a, axis=None, dtype=None, out=None): - return numpy.ndarray([0, 0]) - - @classmethod - def accumulate(cls, array, axis=None, dtype=None, out=None): - return numpy.ndarray([0, 0]) - - @classmethod - def reduceat(cls, a, indices, axis=None, dtype=None, out=None): - return numpy.ndarray([0, 0]) - - @classmethod - def outer(cls, A, B, **kwargs): - return numpy.ndarray([0, 0]) - - @classmethod - def at(cls, a, indices, b=None): - return numpy.ndarray([0, 0]) - - class FakeUfuncOneArg(FakeUfunc): - def __call__(self, x, {opt_args:s}): - return numpy.ndarray([0, 0]) - - class FakeUfuncOneArgBis(FakeUfunc): - def __call__(self, x, {opt_args:s}): - return numpy.ndarray([0, 0]), numpy.ndarray([0, 0]) - - class FakeUfuncTwoArgs(FakeUfunc): - def __call__(self, x1, x2, {opt_args:s}): - return numpy.ndarray([0, 0]) - - # Constants - e = 2.718281828459045 - euler_gamma = 0.5772156649015329 - - # One arg functions with optional kwargs - arccos = FakeUfuncOneArg() - arccosh = FakeUfuncOneArg() - arcsin = FakeUfuncOneArg() - arcsinh = FakeUfuncOneArg() - arctan = FakeUfuncOneArg() - arctanh = FakeUfuncOneArg() - cbrt = FakeUfuncOneArg() - conj = FakeUfuncOneArg() - conjugate = FakeUfuncOneArg() - cosh = FakeUfuncOneArg() - deg2rad = FakeUfuncOneArg() - exp2 = FakeUfuncOneArg() - expm1 = FakeUfuncOneArg() - fabs = FakeUfuncOneArg() - frexp = FakeUfuncOneArgBis() - isfinite = FakeUfuncOneArg() - isinf = FakeUfuncOneArg() - log = FakeUfuncOneArg() - log1p = FakeUfuncOneArg() - log2 = FakeUfuncOneArg() - logical_not = FakeUfuncOneArg() - modf = FakeUfuncOneArgBis() - negative = FakeUfuncOneArg() - positive = FakeUfuncOneArg() - rad2deg = FakeUfuncOneArg() - reciprocal = FakeUfuncOneArg() - rint = FakeUfuncOneArg() - sign = FakeUfuncOneArg() - signbit = FakeUfuncOneArg() - sinh = FakeUfuncOneArg() - spacing = FakeUfuncOneArg() - square = FakeUfuncOneArg() - tan = FakeUfuncOneArg() - tanh = FakeUfuncOneArg() - trunc = FakeUfuncOneArg() - - # Two args functions with optional kwargs - bitwise_and = FakeUfuncTwoArgs() - bitwise_or = FakeUfuncTwoArgs() - bitwise_xor = FakeUfuncTwoArgs() - copysign = FakeUfuncTwoArgs() - divide = FakeUfuncTwoArgs() - divmod = FakeUfuncTwoArgs() - equal = FakeUfuncTwoArgs() - float_power = FakeUfuncTwoArgs() - floor_divide = FakeUfuncTwoArgs() - fmax = FakeUfuncTwoArgs() - fmin = FakeUfuncTwoArgs() - fmod = FakeUfuncTwoArgs() - greater = FakeUfuncTwoArgs() - gcd = FakeUfuncTwoArgs() - hypot = FakeUfuncTwoArgs() - heaviside = FakeUfuncTwoArgs() - lcm = FakeUfuncTwoArgs() - ldexp = FakeUfuncTwoArgs() - left_shift = FakeUfuncTwoArgs() - less = FakeUfuncTwoArgs() - logaddexp = FakeUfuncTwoArgs() - logaddexp2 = FakeUfuncTwoArgs() - logical_and = FakeUfuncTwoArgs() - logical_or = FakeUfuncTwoArgs() - logical_xor = FakeUfuncTwoArgs() - maximum = FakeUfuncTwoArgs() - minimum = FakeUfuncTwoArgs() - nextafter = FakeUfuncTwoArgs() - not_equal = FakeUfuncTwoArgs() - power = FakeUfuncTwoArgs() - remainder = FakeUfuncTwoArgs() - right_shift = FakeUfuncTwoArgs() - subtract = FakeUfuncTwoArgs() - true_divide = FakeUfuncTwoArgs() - """.format( - opt_args=ufunc_optional_keyword_arguments - ) - ) - - -astroid.register_module_extender( - astroid.MANAGER, "numpy.core.umath", numpy_core_umath_transform -) diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_numpy_ndarray.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_numpy_ndarray.py deleted file mode 100644 index d40a7dd..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_numpy_ndarray.py +++ /dev/null @@ -1,153 +0,0 @@ -# Copyright (c) 2015-2016, 2018-2019 Claudiu Popa -# Copyright (c) 2016 Ceridwen -# Copyright (c) 2017-2020 hippo91 - -# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html -# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER - - -"""Astroid hooks for numpy ndarray class.""" - -import functools -import astroid - - -def infer_numpy_ndarray(node, context=None): - ndarray = """ - class ndarray(object): - def __init__(self, shape, dtype=float, buffer=None, offset=0, - strides=None, order=None): - self.T = None - self.base = None - self.ctypes = None - self.data = None - self.dtype = None - self.flags = None - self.flat = None - self.imag = np.ndarray([0, 0]) - self.itemsize = None - self.nbytes = None - self.ndim = None - self.real = np.ndarray([0, 0]) - self.shape = numpy.ndarray([0, 0]) - self.size = None - self.strides = None - - def __abs__(self): return numpy.ndarray([0, 0]) - def __add__(self, value): return numpy.ndarray([0, 0]) - def __and__(self, value): return numpy.ndarray([0, 0]) - def __array__(self, dtype=None): return numpy.ndarray([0, 0]) - def __array_wrap__(self, obj): return numpy.ndarray([0, 0]) - def __contains__(self, key): return True - def __copy__(self): return numpy.ndarray([0, 0]) - def __deepcopy__(self, memo): return numpy.ndarray([0, 0]) - def __divmod__(self, value): return (numpy.ndarray([0, 0]), numpy.ndarray([0, 0])) - def __eq__(self, value): return numpy.ndarray([0, 0]) - def __float__(self): return 0. - def __floordiv__(self): return numpy.ndarray([0, 0]) - def __ge__(self, value): return numpy.ndarray([0, 0]) - def __getitem__(self, key): return uninferable - def __gt__(self, value): return numpy.ndarray([0, 0]) - def __iadd__(self, value): return numpy.ndarray([0, 0]) - def __iand__(self, value): return numpy.ndarray([0, 0]) - def __ifloordiv__(self, value): return numpy.ndarray([0, 0]) - def __ilshift__(self, value): return numpy.ndarray([0, 0]) - def __imod__(self, value): return numpy.ndarray([0, 0]) - def __imul__(self, value): return numpy.ndarray([0, 0]) - def __int__(self): return 0 - def __invert__(self): return numpy.ndarray([0, 0]) - def __ior__(self, value): return numpy.ndarray([0, 0]) - def __ipow__(self, value): return numpy.ndarray([0, 0]) - def __irshift__(self, value): return numpy.ndarray([0, 0]) - def __isub__(self, value): return numpy.ndarray([0, 0]) - def __itruediv__(self, value): return numpy.ndarray([0, 0]) - def __ixor__(self, value): return numpy.ndarray([0, 0]) - def __le__(self, value): return numpy.ndarray([0, 0]) - def __len__(self): return 1 - def __lshift__(self, value): return numpy.ndarray([0, 0]) - def __lt__(self, value): return numpy.ndarray([0, 0]) - def __matmul__(self, value): return numpy.ndarray([0, 0]) - def __mod__(self, value): return numpy.ndarray([0, 0]) - def __mul__(self, value): return numpy.ndarray([0, 0]) - def __ne__(self, value): return numpy.ndarray([0, 0]) - def __neg__(self): return numpy.ndarray([0, 0]) - def __or__(self): return numpy.ndarray([0, 0]) - def __pos__(self): return numpy.ndarray([0, 0]) - def __pow__(self): return numpy.ndarray([0, 0]) - def __repr__(self): return str() - def __rshift__(self): return numpy.ndarray([0, 0]) - def __setitem__(self, key, value): return uninferable - def __str__(self): return str() - def __sub__(self, value): return numpy.ndarray([0, 0]) - def __truediv__(self, value): return numpy.ndarray([0, 0]) - def __xor__(self, value): return numpy.ndarray([0, 0]) - def all(self, axis=None, out=None, keepdims=False): return np.ndarray([0, 0]) - def any(self, axis=None, out=None, keepdims=False): return np.ndarray([0, 0]) - def argmax(self, axis=None, out=None): return np.ndarray([0, 0]) - def argmin(self, axis=None, out=None): return np.ndarray([0, 0]) - def argpartition(self, kth, axis=-1, kind='introselect', order=None): return np.ndarray([0, 0]) - def argsort(self, axis=-1, kind='quicksort', order=None): return np.ndarray([0, 0]) - def astype(self, dtype, order='K', casting='unsafe', subok=True, copy=True): return np.ndarray([0, 0]) - def byteswap(self, inplace=False): return np.ndarray([0, 0]) - def choose(self, choices, out=None, mode='raise'): return np.ndarray([0, 0]) - def clip(self, min=None, max=None, out=None): return np.ndarray([0, 0]) - def compress(self, condition, axis=None, out=None): return np.ndarray([0, 0]) - def conj(self): return np.ndarray([0, 0]) - def conjugate(self): return np.ndarray([0, 0]) - def copy(self, order='C'): return np.ndarray([0, 0]) - def cumprod(self, axis=None, dtype=None, out=None): return np.ndarray([0, 0]) - def cumsum(self, axis=None, dtype=None, out=None): return np.ndarray([0, 0]) - def diagonal(self, offset=0, axis1=0, axis2=1): return np.ndarray([0, 0]) - def dot(self, b, out=None): return np.ndarray([0, 0]) - def dump(self, file): return None - def dumps(self): return str() - def fill(self, value): return None - def flatten(self, order='C'): return np.ndarray([0, 0]) - def getfield(self, dtype, offset=0): return np.ndarray([0, 0]) - def item(self, *args): return uninferable - def itemset(self, *args): return None - def max(self, axis=None, out=None): return np.ndarray([0, 0]) - def mean(self, axis=None, dtype=None, out=None, keepdims=False): return np.ndarray([0, 0]) - def min(self, axis=None, out=None, keepdims=False): return np.ndarray([0, 0]) - def newbyteorder(self, new_order='S'): return np.ndarray([0, 0]) - def nonzero(self): return (1,) - def partition(self, kth, axis=-1, kind='introselect', order=None): return None - def prod(self, axis=None, dtype=None, out=None, keepdims=False): return np.ndarray([0, 0]) - def ptp(self, axis=None, out=None): return np.ndarray([0, 0]) - def put(self, indices, values, mode='raise'): return None - def ravel(self, order='C'): return np.ndarray([0, 0]) - def repeat(self, repeats, axis=None): return np.ndarray([0, 0]) - def reshape(self, shape, order='C'): return np.ndarray([0, 0]) - def resize(self, new_shape, refcheck=True): return None - def round(self, decimals=0, out=None): return np.ndarray([0, 0]) - def searchsorted(self, v, side='left', sorter=None): return np.ndarray([0, 0]) - def setfield(self, val, dtype, offset=0): return None - def setflags(self, write=None, align=None, uic=None): return None - def sort(self, axis=-1, kind='quicksort', order=None): return None - def squeeze(self, axis=None): return np.ndarray([0, 0]) - def std(self, axis=None, dtype=None, out=None, ddof=0, keepdims=False): return np.ndarray([0, 0]) - def sum(self, axis=None, dtype=None, out=None, keepdims=False): return np.ndarray([0, 0]) - def swapaxes(self, axis1, axis2): return np.ndarray([0, 0]) - def take(self, indices, axis=None, out=None, mode='raise'): return np.ndarray([0, 0]) - def tobytes(self, order='C'): return b'' - def tofile(self, fid, sep="", format="%s"): return None - def tolist(self, ): return [] - def tostring(self, order='C'): return b'' - def trace(self, offset=0, axis1=0, axis2=1, dtype=None, out=None): return np.ndarray([0, 0]) - def transpose(self, *axes): return np.ndarray([0, 0]) - def var(self, axis=None, dtype=None, out=None, ddof=0, keepdims=False): return np.ndarray([0, 0]) - def view(self, dtype=None, type=None): return np.ndarray([0, 0]) - """ - node = astroid.extract_node(ndarray) - return node.infer(context=context) - - -def _looks_like_numpy_ndarray(node): - return isinstance(node, astroid.Attribute) and node.attrname == "ndarray" - - -astroid.MANAGER.register_transform( - astroid.Attribute, - astroid.inference_tip(infer_numpy_ndarray), - _looks_like_numpy_ndarray, -) diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_numpy_random_mtrand.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_numpy_random_mtrand.py deleted file mode 100644 index cffdcee..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_numpy_random_mtrand.py +++ /dev/null @@ -1,70 +0,0 @@ -# Copyright (c) 2019 hippo91 - -# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html -# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER - -# TODO(hippo91) : correct the functions return types -"""Astroid hooks for numpy.random.mtrand module.""" - -import astroid - - -def numpy_random_mtrand_transform(): - return astroid.parse( - """ - def beta(a, b, size=None): return uninferable - def binomial(n, p, size=None): return uninferable - def bytes(length): return uninferable - def chisquare(df, size=None): return uninferable - def choice(a, size=None, replace=True, p=None): return uninferable - def dirichlet(alpha, size=None): return uninferable - def exponential(scale=1.0, size=None): return uninferable - def f(dfnum, dfden, size=None): return uninferable - def gamma(shape, scale=1.0, size=None): return uninferable - def geometric(p, size=None): return uninferable - def get_state(): return uninferable - def gumbel(loc=0.0, scale=1.0, size=None): return uninferable - def hypergeometric(ngood, nbad, nsample, size=None): return uninferable - def laplace(loc=0.0, scale=1.0, size=None): return uninferable - def logistic(loc=0.0, scale=1.0, size=None): return uninferable - def lognormal(mean=0.0, sigma=1.0, size=None): return uninferable - def logseries(p, size=None): return uninferable - def multinomial(n, pvals, size=None): return uninferable - def multivariate_normal(mean, cov, size=None): return uninferable - def negative_binomial(n, p, size=None): return uninferable - def noncentral_chisquare(df, nonc, size=None): return uninferable - def noncentral_f(dfnum, dfden, nonc, size=None): return uninferable - def normal(loc=0.0, scale=1.0, size=None): return uninferable - def pareto(a, size=None): return uninferable - def permutation(x): return uninferable - def poisson(lam=1.0, size=None): return uninferable - def power(a, size=None): return uninferable - def rand(*args): return uninferable - def randint(low, high=None, size=None, dtype='l'): - import numpy - return numpy.ndarray((1,1)) - def randn(*args): return uninferable - def random_integers(low, high=None, size=None): return uninferable - def random_sample(size=None): return uninferable - def rayleigh(scale=1.0, size=None): return uninferable - def seed(seed=None): return uninferable - def set_state(state): return uninferable - def shuffle(x): return uninferable - def standard_cauchy(size=None): return uninferable - def standard_exponential(size=None): return uninferable - def standard_gamma(shape, size=None): return uninferable - def standard_normal(size=None): return uninferable - def standard_t(df, size=None): return uninferable - def triangular(left, mode, right, size=None): return uninferable - def uniform(low=0.0, high=1.0, size=None): return uninferable - def vonmises(mu, kappa, size=None): return uninferable - def wald(mean, scale, size=None): return uninferable - def weibull(a, size=None): return uninferable - def zipf(a, size=None): return uninferable - """ - ) - - -astroid.register_module_extender( - astroid.MANAGER, "numpy.random.mtrand", numpy_random_mtrand_transform -) diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_numpy_utils.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_numpy_utils.py deleted file mode 100644 index b29d271..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_numpy_utils.py +++ /dev/null @@ -1,65 +0,0 @@ -# Copyright (c) 2019-2020 hippo91 -# Copyright (c) 2019 Claudiu Popa - -# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html -# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER - - -"""Different utilities for the numpy brains""" - - -import astroid - - -def infer_numpy_member(src, node, context=None): - node = astroid.extract_node(src) - return node.infer(context=context) - - -def _is_a_numpy_module(node: astroid.node_classes.Name) -> bool: - """ - Returns True if the node is a representation of a numpy module. - - For example in : - import numpy as np - x = np.linspace(1, 2) - The node is a representation of the numpy module. - - :param node: node to test - :return: True if the node is a representation of the numpy module. - """ - module_nickname = node.name - potential_import_target = [ - x for x in node.lookup(module_nickname)[1] if isinstance(x, astroid.Import) - ] - for target in potential_import_target: - if ("numpy", module_nickname) in target.names: - return True - return False - - -def looks_like_numpy_member( - member_name: str, node: astroid.node_classes.NodeNG -) -> bool: - """ - Returns True if the node is a member of numpy whose - name is member_name. - - :param member_name: name of the member - :param node: node to test - :return: True if the node is a member of numpy - """ - if ( - isinstance(node, astroid.Attribute) - and node.attrname == member_name - and isinstance(node.expr, astroid.Name) - and _is_a_numpy_module(node.expr) - ): - return True - if ( - isinstance(node, astroid.Name) - and node.name == member_name - and node.root().name.startswith("numpy") - ): - return True - return False diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_pkg_resources.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_pkg_resources.py deleted file mode 100644 index 25e7649..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_pkg_resources.py +++ /dev/null @@ -1,75 +0,0 @@ -# Copyright (c) 2016, 2018 Claudiu Popa -# Copyright (c) 2016 Ceridwen - -# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html -# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER - - -import astroid -from astroid import parse -from astroid import inference_tip -from astroid import register_module_extender -from astroid import MANAGER - - -def pkg_resources_transform(): - return parse( - """ -def require(*requirements): - return pkg_resources.working_set.require(*requirements) - -def run_script(requires, script_name): - return pkg_resources.working_set.run_script(requires, script_name) - -def iter_entry_points(group, name=None): - return pkg_resources.working_set.iter_entry_points(group, name) - -def resource_exists(package_or_requirement, resource_name): - return get_provider(package_or_requirement).has_resource(resource_name) - -def resource_isdir(package_or_requirement, resource_name): - return get_provider(package_or_requirement).resource_isdir( - resource_name) - -def resource_filename(package_or_requirement, resource_name): - return get_provider(package_or_requirement).get_resource_filename( - self, resource_name) - -def resource_stream(package_or_requirement, resource_name): - return get_provider(package_or_requirement).get_resource_stream( - self, resource_name) - -def resource_string(package_or_requirement, resource_name): - return get_provider(package_or_requirement).get_resource_string( - self, resource_name) - -def resource_listdir(package_or_requirement, resource_name): - return get_provider(package_or_requirement).resource_listdir( - resource_name) - -def extraction_error(): - pass - -def get_cache_path(archive_name, names=()): - extract_path = self.extraction_path or get_default_cache() - target_path = os.path.join(extract_path, archive_name+'-tmp', *names) - return target_path - -def postprocess(tempname, filename): - pass - -def set_extraction_path(path): - pass - -def cleanup_resources(force=False): - pass - -def get_distribution(dist): - return Distribution(dist) - -_namespace_packages = {} -""" - ) - - -register_module_extender(MANAGER, "pkg_resources", pkg_resources_transform) diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_pytest.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_pytest.py deleted file mode 100644 index 56202ab..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_pytest.py +++ /dev/null @@ -1,88 +0,0 @@ -# Copyright (c) 2014-2016, 2018 Claudiu Popa -# Copyright (c) 2014 Jeff Quast -# Copyright (c) 2014 Google, Inc. -# Copyright (c) 2016 Florian Bruhin -# Copyright (c) 2016 Ceridwen - -# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html -# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER - -"""Astroid hooks for pytest.""" -from __future__ import absolute_import -from astroid import MANAGER, register_module_extender -from astroid.builder import AstroidBuilder - - -def pytest_transform(): - return AstroidBuilder(MANAGER).string_build( - """ - -try: - import _pytest.mark - import _pytest.recwarn - import _pytest.runner - import _pytest.python - import _pytest.skipping - import _pytest.assertion -except ImportError: - pass -else: - deprecated_call = _pytest.recwarn.deprecated_call - warns = _pytest.recwarn.warns - - exit = _pytest.runner.exit - fail = _pytest.runner.fail - skip = _pytest.runner.skip - importorskip = _pytest.runner.importorskip - - xfail = _pytest.skipping.xfail - mark = _pytest.mark.MarkGenerator() - raises = _pytest.python.raises - - # New in pytest 3.0 - try: - approx = _pytest.python.approx - register_assert_rewrite = _pytest.assertion.register_assert_rewrite - except AttributeError: - pass - - -# Moved in pytest 3.0 - -try: - import _pytest.freeze_support - freeze_includes = _pytest.freeze_support.freeze_includes -except ImportError: - try: - import _pytest.genscript - freeze_includes = _pytest.genscript.freeze_includes - except ImportError: - pass - -try: - import _pytest.debugging - set_trace = _pytest.debugging.pytestPDB().set_trace -except ImportError: - try: - import _pytest.pdb - set_trace = _pytest.pdb.pytestPDB().set_trace - except ImportError: - pass - -try: - import _pytest.fixtures - fixture = _pytest.fixtures.fixture - yield_fixture = _pytest.fixtures.yield_fixture -except ImportError: - try: - import _pytest.python - fixture = _pytest.python.fixture - yield_fixture = _pytest.python.yield_fixture - except ImportError: - pass -""" - ) - - -register_module_extender(MANAGER, "pytest", pytest_transform) -register_module_extender(MANAGER, "py.test", pytest_transform) diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_qt.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_qt.py deleted file mode 100644 index b703b37..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_qt.py +++ /dev/null @@ -1,83 +0,0 @@ -# Copyright (c) 2015-2016, 2018 Claudiu Popa -# Copyright (c) 2016 Ceridwen -# Copyright (c) 2017 Roy Wright -# Copyright (c) 2018 Ashley Whetter -# Copyright (c) 2019 Antoine Boellinger - -# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html -# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER - -"""Astroid hooks for the PyQT library.""" - -from astroid import MANAGER, register_module_extender -from astroid.builder import AstroidBuilder -from astroid import nodes -from astroid import parse - - -def _looks_like_signal(node, signal_name="pyqtSignal"): - if "__class__" in node.instance_attrs: - try: - cls = node.instance_attrs["__class__"][0] - return cls.name == signal_name - except AttributeError: - # return False if the cls does not have a name attribute - pass - return False - - -def transform_pyqt_signal(node): - module = parse( - """ - class pyqtSignal(object): - def connect(self, slot, type=None, no_receiver_check=False): - pass - def disconnect(self, slot): - pass - def emit(self, *args): - pass - """ - ) - signal_cls = module["pyqtSignal"] - node.instance_attrs["emit"] = signal_cls["emit"] - node.instance_attrs["disconnect"] = signal_cls["disconnect"] - node.instance_attrs["connect"] = signal_cls["connect"] - - -def transform_pyside_signal(node): - module = parse( - """ - class NotPySideSignal(object): - def connect(self, receiver, type=None): - pass - def disconnect(self, receiver): - pass - def emit(self, *args): - pass - """ - ) - signal_cls = module["NotPySideSignal"] - node.instance_attrs["connect"] = signal_cls["connect"] - node.instance_attrs["disconnect"] = signal_cls["disconnect"] - node.instance_attrs["emit"] = signal_cls["emit"] - - -def pyqt4_qtcore_transform(): - return AstroidBuilder(MANAGER).string_build( - """ - -def SIGNAL(signal_name): pass - -class QObject(object): - def emit(self, signal): pass -""" - ) - - -register_module_extender(MANAGER, "PyQt4.QtCore", pyqt4_qtcore_transform) -MANAGER.register_transform(nodes.FunctionDef, transform_pyqt_signal, _looks_like_signal) -MANAGER.register_transform( - nodes.ClassDef, - transform_pyside_signal, - lambda node: node.qname() in ("PySide.QtCore.Signal", "PySide2.QtCore.Signal"), -) diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_random.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_random.py deleted file mode 100644 index 5ec858a..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_random.py +++ /dev/null @@ -1,75 +0,0 @@ -# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html -# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER -import random - -import astroid -from astroid import helpers -from astroid import MANAGER - - -ACCEPTED_ITERABLES_FOR_SAMPLE = (astroid.List, astroid.Set, astroid.Tuple) - - -def _clone_node_with_lineno(node, parent, lineno): - cls = node.__class__ - other_fields = node._other_fields - _astroid_fields = node._astroid_fields - init_params = {"lineno": lineno, "col_offset": node.col_offset, "parent": parent} - postinit_params = {param: getattr(node, param) for param in _astroid_fields} - if other_fields: - init_params.update({param: getattr(node, param) for param in other_fields}) - new_node = cls(**init_params) - if hasattr(node, "postinit") and _astroid_fields: - new_node.postinit(**postinit_params) - return new_node - - -def infer_random_sample(node, context=None): - if len(node.args) != 2: - raise astroid.UseInferenceDefault - - length = node.args[1] - if not isinstance(length, astroid.Const): - raise astroid.UseInferenceDefault - if not isinstance(length.value, int): - raise astroid.UseInferenceDefault - - inferred_sequence = helpers.safe_infer(node.args[0], context=context) - if not inferred_sequence: - raise astroid.UseInferenceDefault - - if not isinstance(inferred_sequence, ACCEPTED_ITERABLES_FOR_SAMPLE): - raise astroid.UseInferenceDefault - - if length.value > len(inferred_sequence.elts): - # In this case, this will raise a ValueError - raise astroid.UseInferenceDefault - - try: - elts = random.sample(inferred_sequence.elts, length.value) - except ValueError: - raise astroid.UseInferenceDefault - - new_node = astroid.List( - lineno=node.lineno, col_offset=node.col_offset, parent=node.scope() - ) - new_elts = [ - _clone_node_with_lineno(elt, parent=new_node, lineno=new_node.lineno) - for elt in elts - ] - new_node.postinit(new_elts) - return iter((new_node,)) - - -def _looks_like_random_sample(node): - func = node.func - if isinstance(func, astroid.Attribute): - return func.attrname == "sample" - if isinstance(func, astroid.Name): - return func.name == "sample" - return False - - -MANAGER.register_transform( - astroid.Call, astroid.inference_tip(infer_random_sample), _looks_like_random_sample -) diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_re.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_re.py deleted file mode 100644 index c7ee51a..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_re.py +++ /dev/null @@ -1,36 +0,0 @@ -# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html -# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER -import sys -import astroid - -PY36 = sys.version_info >= (3, 6) - -if PY36: - # Since Python 3.6 there is the RegexFlag enum - # where every entry will be exposed via updating globals() - - def _re_transform(): - return astroid.parse( - """ - import sre_compile - ASCII = sre_compile.SRE_FLAG_ASCII - IGNORECASE = sre_compile.SRE_FLAG_IGNORECASE - LOCALE = sre_compile.SRE_FLAG_LOCALE - UNICODE = sre_compile.SRE_FLAG_UNICODE - MULTILINE = sre_compile.SRE_FLAG_MULTILINE - DOTALL = sre_compile.SRE_FLAG_DOTALL - VERBOSE = sre_compile.SRE_FLAG_VERBOSE - A = ASCII - I = IGNORECASE - L = LOCALE - U = UNICODE - M = MULTILINE - S = DOTALL - X = VERBOSE - TEMPLATE = sre_compile.SRE_FLAG_TEMPLATE - T = TEMPLATE - DEBUG = sre_compile.SRE_FLAG_DEBUG - """ - ) - - astroid.register_module_extender(astroid.MANAGER, "re", _re_transform) diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_responses.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_responses.py deleted file mode 100644 index 3a44129..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_responses.py +++ /dev/null @@ -1,73 +0,0 @@ -""" -Astroid hooks for responses. - -It might need to be manually updated from the public methods of -:class:`responses.RequestsMock`. - -See: https://github.com/getsentry/responses/blob/master/responses.py - -""" -import astroid - - -def responses_funcs(): - return astroid.parse( - """ - DELETE = "DELETE" - GET = "GET" - HEAD = "HEAD" - OPTIONS = "OPTIONS" - PATCH = "PATCH" - POST = "POST" - PUT = "PUT" - response_callback = None - - def reset(): - return - - def add( - method=None, # method or ``Response`` - url=None, - body="", - adding_headers=None, - *args, - **kwargs - ): - return - - def add_passthru(prefix): - return - - def remove(method_or_response=None, url=None): - return - - def replace(method_or_response=None, url=None, body="", *args, **kwargs): - return - - def add_callback( - method, url, callback, match_querystring=False, content_type="text/plain" - ): - return - - calls = [] - - def __enter__(): - return - - def __exit__(type, value, traceback): - success = type is None - return success - - def activate(func): - return func - - def start(): - return - - def stop(allow_assert=True): - return - """ - ) - - -astroid.register_module_extender(astroid.MANAGER, "responses", responses_funcs) diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_scipy_signal.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_scipy_signal.py deleted file mode 100644 index 4d00c6c..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_scipy_signal.py +++ /dev/null @@ -1,89 +0,0 @@ -# Copyright (c) 2019 Valentin Valls - -# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html -# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER - - -"""Astroid hooks for scipy.signal module.""" - -import astroid - - -def scipy_signal(): - return astroid.parse( - """ - # different functions defined in scipy.signals - - def barthann(M, sym=True): - return numpy.ndarray([0]) - - def bartlett(M, sym=True): - return numpy.ndarray([0]) - - def blackman(M, sym=True): - return numpy.ndarray([0]) - - def blackmanharris(M, sym=True): - return numpy.ndarray([0]) - - def bohman(M, sym=True): - return numpy.ndarray([0]) - - def boxcar(M, sym=True): - return numpy.ndarray([0]) - - def chebwin(M, at, sym=True): - return numpy.ndarray([0]) - - def cosine(M, sym=True): - return numpy.ndarray([0]) - - def exponential(M, center=None, tau=1.0, sym=True): - return numpy.ndarray([0]) - - def flattop(M, sym=True): - return numpy.ndarray([0]) - - def gaussian(M, std, sym=True): - return numpy.ndarray([0]) - - def general_gaussian(M, p, sig, sym=True): - return numpy.ndarray([0]) - - def hamming(M, sym=True): - return numpy.ndarray([0]) - - def hann(M, sym=True): - return numpy.ndarray([0]) - - def hanning(M, sym=True): - return numpy.ndarray([0]) - - def impulse2(system, X0=None, T=None, N=None, **kwargs): - return numpy.ndarray([0]), numpy.ndarray([0]) - - def kaiser(M, beta, sym=True): - return numpy.ndarray([0]) - - def nuttall(M, sym=True): - return numpy.ndarray([0]) - - def parzen(M, sym=True): - return numpy.ndarray([0]) - - def slepian(M, width, sym=True): - return numpy.ndarray([0]) - - def step2(system, X0=None, T=None, N=None, **kwargs): - return numpy.ndarray([0]), numpy.ndarray([0]) - - def triang(M, sym=True): - return numpy.ndarray([0]) - - def tukey(M, alpha=0.5, sym=True): - return numpy.ndarray([0]) - """ - ) - - -astroid.register_module_extender(astroid.MANAGER, "scipy.signal", scipy_signal) diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_six.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_six.py deleted file mode 100644 index 46d9fa3..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_six.py +++ /dev/null @@ -1,201 +0,0 @@ -# Copyright (c) 2014-2016, 2018, 2020 Claudiu Popa -# Copyright (c) 2015-2016 Ceridwen -# Copyright (c) 2018 Bryce Guinta - -# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html -# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER - - -"""Astroid hooks for six module.""" - -from textwrap import dedent - -from astroid import MANAGER, register_module_extender -from astroid.builder import AstroidBuilder -from astroid.exceptions import ( - AstroidBuildingError, - InferenceError, - AttributeInferenceError, -) -from astroid import nodes - - -SIX_ADD_METACLASS = "six.add_metaclass" - - -def _indent(text, prefix, predicate=None): - """Adds 'prefix' to the beginning of selected lines in 'text'. - - If 'predicate' is provided, 'prefix' will only be added to the lines - where 'predicate(line)' is True. If 'predicate' is not provided, - it will default to adding 'prefix' to all non-empty lines that do not - consist solely of whitespace characters. - """ - if predicate is None: - predicate = lambda line: line.strip() - - def prefixed_lines(): - for line in text.splitlines(True): - yield prefix + line if predicate(line) else line - - return "".join(prefixed_lines()) - - -_IMPORTS = """ -import _io -cStringIO = _io.StringIO -filter = filter -from itertools import filterfalse -input = input -from sys import intern -map = map -range = range -from importlib import reload -reload_module = lambda module: reload(module) -from functools import reduce -from shlex import quote as shlex_quote -from io import StringIO -from collections import UserDict, UserList, UserString -xrange = range -zip = zip -from itertools import zip_longest -import builtins -import configparser -import copyreg -import _dummy_thread -import http.cookiejar as http_cookiejar -import http.cookies as http_cookies -import html.entities as html_entities -import html.parser as html_parser -import http.client as http_client -import http.server as http_server -BaseHTTPServer = CGIHTTPServer = SimpleHTTPServer = http.server -import pickle as cPickle -import queue -import reprlib -import socketserver -import _thread -import winreg -import xmlrpc.server as xmlrpc_server -import xmlrpc.client as xmlrpc_client -import urllib.robotparser as urllib_robotparser -import email.mime.multipart as email_mime_multipart -import email.mime.nonmultipart as email_mime_nonmultipart -import email.mime.text as email_mime_text -import email.mime.base as email_mime_base -import urllib.parse as urllib_parse -import urllib.error as urllib_error -import tkinter -import tkinter.dialog as tkinter_dialog -import tkinter.filedialog as tkinter_filedialog -import tkinter.scrolledtext as tkinter_scrolledtext -import tkinter.simpledialog as tkinder_simpledialog -import tkinter.tix as tkinter_tix -import tkinter.ttk as tkinter_ttk -import tkinter.constants as tkinter_constants -import tkinter.dnd as tkinter_dnd -import tkinter.colorchooser as tkinter_colorchooser -import tkinter.commondialog as tkinter_commondialog -import tkinter.filedialog as tkinter_tkfiledialog -import tkinter.font as tkinter_font -import tkinter.messagebox as tkinter_messagebox -import urllib -import urllib.request as urllib_request -import urllib.robotparser as urllib_robotparser -import urllib.parse as urllib_parse -import urllib.error as urllib_error -""" - - -def six_moves_transform(): - code = dedent( - """ - class Moves(object): - {} - moves = Moves() - """ - ).format(_indent(_IMPORTS, " ")) - module = AstroidBuilder(MANAGER).string_build(code) - module.name = "six.moves" - return module - - -def _six_fail_hook(modname): - """Fix six.moves imports due to the dynamic nature of this - class. - - Construct a pseudo-module which contains all the necessary imports - for six - - :param modname: Name of failed module - :type modname: str - - :return: An astroid module - :rtype: nodes.Module - """ - - attribute_of = modname != "six.moves" and modname.startswith("six.moves") - if modname != "six.moves" and not attribute_of: - raise AstroidBuildingError(modname=modname) - module = AstroidBuilder(MANAGER).string_build(_IMPORTS) - module.name = "six.moves" - if attribute_of: - # Facilitate import of submodules in Moves - start_index = len(module.name) - attribute = modname[start_index:].lstrip(".").replace(".", "_") - try: - import_attr = module.getattr(attribute)[0] - except AttributeInferenceError: - raise AstroidBuildingError(modname=modname) - if isinstance(import_attr, nodes.Import): - submodule = MANAGER.ast_from_module_name(import_attr.names[0][0]) - return submodule - # Let dummy submodule imports pass through - # This will cause an Uninferable result, which is okay - return module - - -def _looks_like_decorated_with_six_add_metaclass(node): - if not node.decorators: - return False - - for decorator in node.decorators.nodes: - if not isinstance(decorator, nodes.Call): - continue - if decorator.func.as_string() == SIX_ADD_METACLASS: - return True - return False - - -def transform_six_add_metaclass(node): - """Check if the given class node is decorated with *six.add_metaclass* - - If so, inject its argument as the metaclass of the underlying class. - """ - if not node.decorators: - return - - for decorator in node.decorators.nodes: - if not isinstance(decorator, nodes.Call): - continue - - try: - func = next(decorator.func.infer()) - except InferenceError: - continue - if func.qname() == SIX_ADD_METACLASS and decorator.args: - metaclass = decorator.args[0] - node._metaclass = metaclass - return node - - -register_module_extender(MANAGER, "six", six_moves_transform) -register_module_extender( - MANAGER, "requests.packages.urllib3.packages.six", six_moves_transform -) -MANAGER.register_failed_import_hook(_six_fail_hook) -MANAGER.register_transform( - nodes.ClassDef, - transform_six_add_metaclass, - _looks_like_decorated_with_six_add_metaclass, -) diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_ssl.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_ssl.py deleted file mode 100644 index 2ae21c3..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_ssl.py +++ /dev/null @@ -1,75 +0,0 @@ -# Copyright (c) 2016, 2018 Claudiu Popa -# Copyright (c) 2016 Ceridwen -# Copyright (c) 2019 Benjamin Elven <25181435+S3ntinelX@users.noreply.github.com> - -# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html -# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER - -"""Astroid hooks for the ssl library.""" - -from astroid import MANAGER, register_module_extender -from astroid.builder import AstroidBuilder -from astroid import nodes -from astroid import parse - - -def ssl_transform(): - return parse( - """ - from _ssl import OPENSSL_VERSION_NUMBER, OPENSSL_VERSION_INFO, OPENSSL_VERSION - from _ssl import _SSLContext, MemoryBIO - from _ssl import ( - SSLError, SSLZeroReturnError, SSLWantReadError, SSLWantWriteError, - SSLSyscallError, SSLEOFError, - ) - from _ssl import CERT_NONE, CERT_OPTIONAL, CERT_REQUIRED - from _ssl import txt2obj as _txt2obj, nid2obj as _nid2obj - from _ssl import RAND_status, RAND_add, RAND_bytes, RAND_pseudo_bytes - try: - from _ssl import RAND_egd - except ImportError: - # LibreSSL does not provide RAND_egd - pass - from _ssl import (OP_ALL, OP_CIPHER_SERVER_PREFERENCE, - OP_NO_COMPRESSION, OP_NO_SSLv2, OP_NO_SSLv3, - OP_NO_TLSv1, OP_NO_TLSv1_1, OP_NO_TLSv1_2, - OP_SINGLE_DH_USE, OP_SINGLE_ECDH_USE) - - from _ssl import (ALERT_DESCRIPTION_ACCESS_DENIED, ALERT_DESCRIPTION_BAD_CERTIFICATE, - ALERT_DESCRIPTION_BAD_CERTIFICATE_HASH_VALUE, - ALERT_DESCRIPTION_BAD_CERTIFICATE_STATUS_RESPONSE, - ALERT_DESCRIPTION_BAD_RECORD_MAC, - ALERT_DESCRIPTION_CERTIFICATE_EXPIRED, - ALERT_DESCRIPTION_CERTIFICATE_REVOKED, - ALERT_DESCRIPTION_CERTIFICATE_UNKNOWN, - ALERT_DESCRIPTION_CERTIFICATE_UNOBTAINABLE, - ALERT_DESCRIPTION_CLOSE_NOTIFY, ALERT_DESCRIPTION_DECODE_ERROR, - ALERT_DESCRIPTION_DECOMPRESSION_FAILURE, - ALERT_DESCRIPTION_DECRYPT_ERROR, - ALERT_DESCRIPTION_HANDSHAKE_FAILURE, - ALERT_DESCRIPTION_ILLEGAL_PARAMETER, - ALERT_DESCRIPTION_INSUFFICIENT_SECURITY, - ALERT_DESCRIPTION_INTERNAL_ERROR, - ALERT_DESCRIPTION_NO_RENEGOTIATION, - ALERT_DESCRIPTION_PROTOCOL_VERSION, - ALERT_DESCRIPTION_RECORD_OVERFLOW, - ALERT_DESCRIPTION_UNEXPECTED_MESSAGE, - ALERT_DESCRIPTION_UNKNOWN_CA, - ALERT_DESCRIPTION_UNKNOWN_PSK_IDENTITY, - ALERT_DESCRIPTION_UNRECOGNIZED_NAME, - ALERT_DESCRIPTION_UNSUPPORTED_CERTIFICATE, - ALERT_DESCRIPTION_UNSUPPORTED_EXTENSION, - ALERT_DESCRIPTION_USER_CANCELLED) - from _ssl import (SSL_ERROR_EOF, SSL_ERROR_INVALID_ERROR_CODE, SSL_ERROR_SSL, - SSL_ERROR_SYSCALL, SSL_ERROR_WANT_CONNECT, SSL_ERROR_WANT_READ, - SSL_ERROR_WANT_WRITE, SSL_ERROR_WANT_X509_LOOKUP, SSL_ERROR_ZERO_RETURN) - from _ssl import VERIFY_CRL_CHECK_CHAIN, VERIFY_CRL_CHECK_LEAF, VERIFY_DEFAULT, VERIFY_X509_STRICT - from _ssl import HAS_SNI, HAS_ECDH, HAS_NPN, HAS_ALPN - from _ssl import _OPENSSL_API_VERSION - from _ssl import PROTOCOL_SSLv23, PROTOCOL_TLSv1, PROTOCOL_TLSv1_1, PROTOCOL_TLSv1_2 - from _ssl import PROTOCOL_TLS, PROTOCOL_TLS_CLIENT, PROTOCOL_TLS_SERVER - """ - ) - - -register_module_extender(MANAGER, "ssl", ssl_transform) diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_subprocess.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_subprocess.py deleted file mode 100644 index ab7d5d7..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_subprocess.py +++ /dev/null @@ -1,146 +0,0 @@ -# Copyright (c) 2016-2020 Claudiu Popa -# Copyright (c) 2017 Hugo -# Copyright (c) 2018 Peter Talley -# Copyright (c) 2018 Bryce Guinta -# Copyright (c) 2019 Hugo van Kemenade - -# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html -# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER - -import sys -import textwrap - -import astroid - - -PY37 = sys.version_info >= (3, 7) -PY36 = sys.version_info >= (3, 6) - - -def _subprocess_transform(): - communicate = (bytes("string", "ascii"), bytes("string", "ascii")) - communicate_signature = "def communicate(self, input=None, timeout=None)" - if PY37: - init = """ - def __init__(self, args, bufsize=0, executable=None, - stdin=None, stdout=None, stderr=None, - preexec_fn=None, close_fds=False, shell=False, - cwd=None, env=None, universal_newlines=False, - startupinfo=None, creationflags=0, restore_signals=True, - start_new_session=False, pass_fds=(), *, - encoding=None, errors=None, text=None): - pass - """ - elif PY36: - init = """ - def __init__(self, args, bufsize=0, executable=None, - stdin=None, stdout=None, stderr=None, - preexec_fn=None, close_fds=False, shell=False, - cwd=None, env=None, universal_newlines=False, - startupinfo=None, creationflags=0, restore_signals=True, - start_new_session=False, pass_fds=(), *, - encoding=None, errors=None): - pass - """ - else: - init = """ - def __init__(self, args, bufsize=0, executable=None, - stdin=None, stdout=None, stderr=None, - preexec_fn=None, close_fds=False, shell=False, - cwd=None, env=None, universal_newlines=False, - startupinfo=None, creationflags=0, restore_signals=True, - start_new_session=False, pass_fds=()): - pass - """ - wait_signature = "def wait(self, timeout=None)" - ctx_manager = """ - def __enter__(self): return self - def __exit__(self, *args): pass - """ - py3_args = "args = []" - - if PY37: - check_output_signature = """ - check_output( - args, *, - stdin=None, - stderr=None, - shell=False, - cwd=None, - encoding=None, - errors=None, - universal_newlines=False, - timeout=None, - env=None, - text=None, - restore_signals=True, - preexec_fn=None, - pass_fds=(), - input=None, - start_new_session=False - ): - """.strip() - else: - check_output_signature = """ - check_output( - args, *, - stdin=None, - stderr=None, - shell=False, - cwd=None, - encoding=None, - errors=None, - universal_newlines=False, - timeout=None, - env=None, - restore_signals=True, - preexec_fn=None, - pass_fds=(), - input=None, - start_new_session=False - ): - """.strip() - - code = textwrap.dedent( - """ - def %(check_output_signature)s - if universal_newlines: - return "" - return b"" - - class Popen(object): - returncode = pid = 0 - stdin = stdout = stderr = file() - %(py3_args)s - - %(communicate_signature)s: - return %(communicate)r - %(wait_signature)s: - return self.returncode - def poll(self): - return self.returncode - def send_signal(self, signal): - pass - def terminate(self): - pass - def kill(self): - pass - %(ctx_manager)s - """ - % { - "check_output_signature": check_output_signature, - "communicate": communicate, - "communicate_signature": communicate_signature, - "wait_signature": wait_signature, - "ctx_manager": ctx_manager, - "py3_args": py3_args, - } - ) - - init_lines = textwrap.dedent(init).splitlines() - indented_init = "\n".join(" " * 4 + line for line in init_lines) - code += indented_init - return astroid.parse(code) - - -astroid.register_module_extender(astroid.MANAGER, "subprocess", _subprocess_transform) diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_threading.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_threading.py deleted file mode 100644 index ba3085b..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_threading.py +++ /dev/null @@ -1,31 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright (c) 2016, 2018-2019 Claudiu Popa -# Copyright (c) 2017 Łukasz Rogalski - -# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html -# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER -import astroid - - -def _thread_transform(): - return astroid.parse( - """ - class lock(object): - def acquire(self, blocking=True, timeout=-1): - return False - def release(self): - pass - def __enter__(self): - return True - def __exit__(self, *args): - pass - def locked(self): - return False - - def Lock(): - return lock() - """ - ) - - -astroid.register_module_extender(astroid.MANAGER, "threading", _thread_transform) diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_typing.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_typing.py deleted file mode 100644 index 9ff7227..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_typing.py +++ /dev/null @@ -1,96 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright (c) 2017-2018 Claudiu Popa -# Copyright (c) 2017 Łukasz Rogalski -# Copyright (c) 2017 David Euresti -# Copyright (c) 2018 Bryce Guinta - -"""Astroid hooks for typing.py support.""" -import typing - -from astroid import ( - MANAGER, - UseInferenceDefault, - extract_node, - inference_tip, - nodes, - InferenceError, -) - - -TYPING_NAMEDTUPLE_BASENAMES = {"NamedTuple", "typing.NamedTuple"} -TYPING_TYPEVARS = {"TypeVar", "NewType"} -TYPING_TYPEVARS_QUALIFIED = {"typing.TypeVar", "typing.NewType"} -TYPING_TYPE_TEMPLATE = """ -class Meta(type): - def __getitem__(self, item): - return self - - @property - def __args__(self): - return () - -class {0}(metaclass=Meta): - pass -""" -TYPING_MEMBERS = set(typing.__all__) - - -def looks_like_typing_typevar_or_newtype(node): - func = node.func - if isinstance(func, nodes.Attribute): - return func.attrname in TYPING_TYPEVARS - if isinstance(func, nodes.Name): - return func.name in TYPING_TYPEVARS - return False - - -def infer_typing_typevar_or_newtype(node, context=None): - """Infer a typing.TypeVar(...) or typing.NewType(...) call""" - try: - func = next(node.func.infer(context=context)) - except InferenceError as exc: - raise UseInferenceDefault from exc - - if func.qname() not in TYPING_TYPEVARS_QUALIFIED: - raise UseInferenceDefault - if not node.args: - raise UseInferenceDefault - - typename = node.args[0].as_string().strip("'") - node = extract_node(TYPING_TYPE_TEMPLATE.format(typename)) - return node.infer(context=context) - - -def _looks_like_typing_subscript(node): - """Try to figure out if a Subscript node *might* be a typing-related subscript""" - if isinstance(node, nodes.Name): - return node.name in TYPING_MEMBERS - elif isinstance(node, nodes.Attribute): - return node.attrname in TYPING_MEMBERS - elif isinstance(node, nodes.Subscript): - return _looks_like_typing_subscript(node.value) - return False - - -def infer_typing_attr(node, context=None): - """Infer a typing.X[...] subscript""" - try: - value = next(node.value.infer()) - except InferenceError as exc: - raise UseInferenceDefault from exc - - if not value.qname().startswith("typing."): - raise UseInferenceDefault - - node = extract_node(TYPING_TYPE_TEMPLATE.format(value.qname().split(".")[-1])) - return node.infer(context=context) - - -MANAGER.register_transform( - nodes.Call, - inference_tip(infer_typing_typevar_or_newtype), - looks_like_typing_typevar_or_newtype, -) -MANAGER.register_transform( - nodes.Subscript, inference_tip(infer_typing_attr), _looks_like_typing_subscript -) diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_uuid.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_uuid.py deleted file mode 100644 index 5a33fc2..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/brain/brain_uuid.py +++ /dev/null @@ -1,20 +0,0 @@ -# Copyright (c) 2017-2018 Claudiu Popa - -# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html -# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER - -"""Astroid hooks for the UUID module.""" - - -from astroid import MANAGER -from astroid import nodes - - -def _patch_uuid_class(node): - # The .int member is patched using __dict__ - node.locals["int"] = [nodes.Const(0, parent=node)] - - -MANAGER.register_transform( - nodes.ClassDef, _patch_uuid_class, lambda node: node.qname() == "uuid.UUID" -) diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/builder.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/builder.py deleted file mode 100644 index 142764b..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/builder.py +++ /dev/null @@ -1,455 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright (c) 2006-2011, 2013-2014 LOGILAB S.A. (Paris, FRANCE) -# Copyright (c) 2013 Phil Schaf -# Copyright (c) 2014-2019 Claudiu Popa -# Copyright (c) 2014-2015 Google, Inc. -# Copyright (c) 2014 Alexander Presnyakov -# Copyright (c) 2015-2016 Ceridwen -# Copyright (c) 2016 Derek Gustafson -# Copyright (c) 2017 Łukasz Rogalski -# Copyright (c) 2018 Anthony Sottile - -# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html -# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER - -"""The AstroidBuilder makes astroid from living object and / or from _ast - -The builder is not thread safe and can't be used to parse different sources -at the same time. -""" - -import os -import textwrap -from tokenize import detect_encoding - -from astroid._ast import get_parser_module -from astroid import bases -from astroid import exceptions -from astroid import manager -from astroid import modutils -from astroid import raw_building -from astroid import rebuilder -from astroid import nodes -from astroid import util - -objects = util.lazy_import("objects") - -# The name of the transient function that is used to -# wrap expressions to be extracted when calling -# extract_node. -_TRANSIENT_FUNCTION = "__" - -# The comment used to select a statement to be extracted -# when calling extract_node. -_STATEMENT_SELECTOR = "#@" -MISPLACED_TYPE_ANNOTATION_ERROR = "misplaced type annotation" -MANAGER = manager.AstroidManager() - - -def open_source_file(filename): - with open(filename, "rb") as byte_stream: - encoding = detect_encoding(byte_stream.readline)[0] - stream = open(filename, "r", newline=None, encoding=encoding) - data = stream.read() - return stream, encoding, data - - -def _can_assign_attr(node, attrname): - try: - slots = node.slots() - except NotImplementedError: - pass - else: - if slots and attrname not in {slot.value for slot in slots}: - return False - return True - - -class AstroidBuilder(raw_building.InspectBuilder): - """Class for building an astroid tree from source code or from a live module. - - The param *manager* specifies the manager class which should be used. - If no manager is given, then the default one will be used. The - param *apply_transforms* determines if the transforms should be - applied after the tree was built from source or from a live object, - by default being True. - """ - - # pylint: disable=redefined-outer-name - def __init__(self, manager=None, apply_transforms=True): - super().__init__() - self._manager = manager or MANAGER - self._apply_transforms = apply_transforms - - def module_build(self, module, modname=None): - """Build an astroid from a living module instance.""" - node = None - path = getattr(module, "__file__", None) - if path is not None: - path_, ext = os.path.splitext(modutils._path_from_filename(path)) - if ext in (".py", ".pyc", ".pyo") and os.path.exists(path_ + ".py"): - node = self.file_build(path_ + ".py", modname) - if node is None: - # this is a built-in module - # get a partial representation by introspection - node = self.inspect_build(module, modname=modname, path=path) - if self._apply_transforms: - # We have to handle transformation by ourselves since the - # rebuilder isn't called for builtin nodes - node = self._manager.visit_transforms(node) - return node - - def file_build(self, path, modname=None): - """Build astroid from a source code file (i.e. from an ast) - - *path* is expected to be a python source file - """ - try: - stream, encoding, data = open_source_file(path) - except IOError as exc: - raise exceptions.AstroidBuildingError( - "Unable to load file {path}:\n{error}", - modname=modname, - path=path, - error=exc, - ) from exc - except (SyntaxError, LookupError) as exc: - raise exceptions.AstroidSyntaxError( - "Python 3 encoding specification error or unknown encoding:\n" - "{error}", - modname=modname, - path=path, - error=exc, - ) from exc - except UnicodeError as exc: # wrong encoding - # detect_encoding returns utf-8 if no encoding specified - raise exceptions.AstroidBuildingError( - "Wrong or no encoding specified for {filename}.", filename=path - ) from exc - with stream: - # get module name if necessary - if modname is None: - try: - modname = ".".join(modutils.modpath_from_file(path)) - except ImportError: - modname = os.path.splitext(os.path.basename(path))[0] - # build astroid representation - module = self._data_build(data, modname, path) - return self._post_build(module, encoding) - - def string_build(self, data, modname="", path=None): - """Build astroid from source code string.""" - module = self._data_build(data, modname, path) - module.file_bytes = data.encode("utf-8") - return self._post_build(module, "utf-8") - - def _post_build(self, module, encoding): - """Handles encoding and delayed nodes after a module has been built""" - module.file_encoding = encoding - self._manager.cache_module(module) - # post tree building steps after we stored the module in the cache: - for from_node in module._import_from_nodes: - if from_node.modname == "__future__": - for symbol, _ in from_node.names: - module.future_imports.add(symbol) - self.add_from_names_to_locals(from_node) - # handle delayed assattr nodes - for delayed in module._delayed_assattr: - self.delayed_assattr(delayed) - - # Visit the transforms - if self._apply_transforms: - module = self._manager.visit_transforms(module) - return module - - def _data_build(self, data, modname, path): - """Build tree node from data and add some informations""" - try: - node, parser_module = _parse_string(data, type_comments=True) - except (TypeError, ValueError, SyntaxError) as exc: - raise exceptions.AstroidSyntaxError( - "Parsing Python code failed:\n{error}", - source=data, - modname=modname, - path=path, - error=exc, - ) from exc - - if path is not None: - node_file = os.path.abspath(path) - else: - node_file = "" - if modname.endswith(".__init__"): - modname = modname[:-9] - package = True - else: - package = ( - path is not None - and os.path.splitext(os.path.basename(path))[0] == "__init__" - ) - builder = rebuilder.TreeRebuilder(self._manager, parser_module) - module = builder.visit_module(node, modname, node_file, package) - module._import_from_nodes = builder._import_from_nodes - module._delayed_assattr = builder._delayed_assattr - return module - - def add_from_names_to_locals(self, node): - """Store imported names to the locals - - Resort the locals if coming from a delayed node - """ - _key_func = lambda node: node.fromlineno - - def sort_locals(my_list): - my_list.sort(key=_key_func) - - for (name, asname) in node.names: - if name == "*": - try: - imported = node.do_import_module() - except exceptions.AstroidBuildingError: - continue - for name in imported.public_names(): - node.parent.set_local(name, node) - sort_locals(node.parent.scope().locals[name]) - else: - node.parent.set_local(asname or name, node) - sort_locals(node.parent.scope().locals[asname or name]) - - def delayed_assattr(self, node): - """Visit a AssAttr node - - This adds name to locals and handle members definition. - """ - try: - frame = node.frame() - for inferred in node.expr.infer(): - if inferred is util.Uninferable: - continue - try: - cls = inferred.__class__ - if cls is bases.Instance or cls is objects.ExceptionInstance: - inferred = inferred._proxied - iattrs = inferred.instance_attrs - if not _can_assign_attr(inferred, node.attrname): - continue - elif isinstance(inferred, bases.Instance): - # Const, Tuple or other containers that inherit from - # `Instance` - continue - elif inferred.is_function: - iattrs = inferred.instance_attrs - else: - iattrs = inferred.locals - except AttributeError: - # XXX log error - continue - values = iattrs.setdefault(node.attrname, []) - if node in values: - continue - # get assign in __init__ first XXX useful ? - if ( - frame.name == "__init__" - and values - and values[0].frame().name != "__init__" - ): - values.insert(0, node) - else: - values.append(node) - except exceptions.InferenceError: - pass - - -def build_namespace_package_module(name, path): - return nodes.Module(name, doc="", path=path, package=True) - - -def parse(code, module_name="", path=None, apply_transforms=True): - """Parses a source string in order to obtain an astroid AST from it - - :param str code: The code for the module. - :param str module_name: The name for the module, if any - :param str path: The path for the module - :param bool apply_transforms: - Apply the transforms for the give code. Use it if you - don't want the default transforms to be applied. - """ - code = textwrap.dedent(code) - builder = AstroidBuilder(manager=MANAGER, apply_transforms=apply_transforms) - return builder.string_build(code, modname=module_name, path=path) - - -def _extract_expressions(node): - """Find expressions in a call to _TRANSIENT_FUNCTION and extract them. - - The function walks the AST recursively to search for expressions that - are wrapped into a call to _TRANSIENT_FUNCTION. If it finds such an - expression, it completely removes the function call node from the tree, - replacing it by the wrapped expression inside the parent. - - :param node: An astroid node. - :type node: astroid.bases.NodeNG - :yields: The sequence of wrapped expressions on the modified tree - expression can be found. - """ - if ( - isinstance(node, nodes.Call) - and isinstance(node.func, nodes.Name) - and node.func.name == _TRANSIENT_FUNCTION - ): - real_expr = node.args[0] - real_expr.parent = node.parent - # Search for node in all _astng_fields (the fields checked when - # get_children is called) of its parent. Some of those fields may - # be lists or tuples, in which case the elements need to be checked. - # When we find it, replace it by real_expr, so that the AST looks - # like no call to _TRANSIENT_FUNCTION ever took place. - for name in node.parent._astroid_fields: - child = getattr(node.parent, name) - if isinstance(child, (list, tuple)): - for idx, compound_child in enumerate(child): - if compound_child is node: - child[idx] = real_expr - elif child is node: - setattr(node.parent, name, real_expr) - yield real_expr - else: - for child in node.get_children(): - yield from _extract_expressions(child) - - -def _find_statement_by_line(node, line): - """Extracts the statement on a specific line from an AST. - - If the line number of node matches line, it will be returned; - otherwise its children are iterated and the function is called - recursively. - - :param node: An astroid node. - :type node: astroid.bases.NodeNG - :param line: The line number of the statement to extract. - :type line: int - :returns: The statement on the line, or None if no statement for the line - can be found. - :rtype: astroid.bases.NodeNG or None - """ - if isinstance(node, (nodes.ClassDef, nodes.FunctionDef)): - # This is an inaccuracy in the AST: the nodes that can be - # decorated do not carry explicit information on which line - # the actual definition (class/def), but .fromline seems to - # be close enough. - node_line = node.fromlineno - else: - node_line = node.lineno - - if node_line == line: - return node - - for child in node.get_children(): - result = _find_statement_by_line(child, line) - if result: - return result - - return None - - -def extract_node(code, module_name=""): - """Parses some Python code as a module and extracts a designated AST node. - - Statements: - To extract one or more statement nodes, append #@ to the end of the line - - Examples: - >>> def x(): - >>> def y(): - >>> return 1 #@ - - The return statement will be extracted. - - >>> class X(object): - >>> def meth(self): #@ - >>> pass - - The function object 'meth' will be extracted. - - Expressions: - To extract arbitrary expressions, surround them with the fake - function call __(...). After parsing, the surrounded expression - will be returned and the whole AST (accessible via the returned - node's parent attribute) will look like the function call was - never there in the first place. - - Examples: - >>> a = __(1) - - The const node will be extracted. - - >>> def x(d=__(foo.bar)): pass - - The node containing the default argument will be extracted. - - >>> def foo(a, b): - >>> return 0 < __(len(a)) < b - - The node containing the function call 'len' will be extracted. - - If no statements or expressions are selected, the last toplevel - statement will be returned. - - If the selected statement is a discard statement, (i.e. an expression - turned into a statement), the wrapped expression is returned instead. - - For convenience, singleton lists are unpacked. - - :param str code: A piece of Python code that is parsed as - a module. Will be passed through textwrap.dedent first. - :param str module_name: The name of the module. - :returns: The designated node from the parse tree, or a list of nodes. - :rtype: astroid.bases.NodeNG, or a list of nodes. - """ - - def _extract(node): - if isinstance(node, nodes.Expr): - return node.value - - return node - - requested_lines = [] - for idx, line in enumerate(code.splitlines()): - if line.strip().endswith(_STATEMENT_SELECTOR): - requested_lines.append(idx + 1) - - tree = parse(code, module_name=module_name) - if not tree.body: - raise ValueError("Empty tree, cannot extract from it") - - extracted = [] - if requested_lines: - extracted = [_find_statement_by_line(tree, line) for line in requested_lines] - - # Modifies the tree. - extracted.extend(_extract_expressions(tree)) - - if not extracted: - extracted.append(tree.body[-1]) - - extracted = [_extract(node) for node in extracted] - if len(extracted) == 1: - return extracted[0] - return extracted - - -def _parse_string(data, type_comments=True): - parser_module = get_parser_module(type_comments=type_comments) - try: - parsed = parser_module.parse(data + "\n", type_comments=type_comments) - except SyntaxError as exc: - # If the type annotations are misplaced for some reason, we do not want - # to fail the entire parsing of the file, so we need to retry the parsing without - # type comment support. - if exc.args[0] != MISPLACED_TYPE_ANNOTATION_ERROR or not type_comments: - raise - - parser_module = get_parser_module(type_comments=False) - parsed = parser_module.parse(data + "\n", type_comments=False) - return parsed, parser_module diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/context.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/context.py deleted file mode 100644 index 40cebf2..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/context.py +++ /dev/null @@ -1,179 +0,0 @@ -# Copyright (c) 2015-2016, 2018-2019 Claudiu Popa -# Copyright (c) 2015-2016 Ceridwen -# Copyright (c) 2018 Bryce Guinta -# Copyright (c) 2018 Nick Drozd - -# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html -# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER - -"""Various context related utilities, including inference and call contexts.""" -import contextlib -import pprint -from typing import Optional - - -class InferenceContext: - """Provide context for inference - - Store already inferred nodes to save time - Account for already visited nodes to infinite stop infinite recursion - """ - - __slots__ = ( - "path", - "lookupname", - "callcontext", - "boundnode", - "inferred", - "extra_context", - ) - - def __init__(self, path=None, inferred=None): - self.path = path or set() - """ - :type: set(tuple(NodeNG, optional(str))) - - Path of visited nodes and their lookupname - - Currently this key is ``(node, context.lookupname)`` - """ - self.lookupname = None - """ - :type: optional[str] - - The original name of the node - - e.g. - foo = 1 - The inference of 'foo' is nodes.Const(1) but the lookup name is 'foo' - """ - self.callcontext = None - """ - :type: optional[CallContext] - - The call arguments and keywords for the given context - """ - self.boundnode = None - """ - :type: optional[NodeNG] - - The bound node of the given context - - e.g. the bound node of object.__new__(cls) is the object node - """ - self.inferred = inferred or {} - """ - :type: dict(seq, seq) - - Inferred node contexts to their mapped results - Currently the key is ``(node, lookupname, callcontext, boundnode)`` - and the value is tuple of the inferred results - """ - self.extra_context = {} - """ - :type: dict(NodeNG, Context) - - Context that needs to be passed down through call stacks - for call arguments - """ - - def push(self, node): - """Push node into inference path - - :return: True if node is already in context path else False - :rtype: bool - - Allows one to see if the given node has already - been looked at for this inference context""" - name = self.lookupname - if (node, name) in self.path: - return True - - self.path.add((node, name)) - return False - - def clone(self): - """Clone inference path - - For example, each side of a binary operation (BinOp) - starts with the same context but diverge as each side is inferred - so the InferenceContext will need be cloned""" - # XXX copy lookupname/callcontext ? - clone = InferenceContext(self.path, inferred=self.inferred) - clone.callcontext = self.callcontext - clone.boundnode = self.boundnode - clone.extra_context = self.extra_context - return clone - - def cache_generator(self, key, generator): - """Cache result of generator into dictionary - - Used to cache inference results""" - results = [] - for result in generator: - results.append(result) - yield result - - self.inferred[key] = tuple(results) - - @contextlib.contextmanager - def restore_path(self): - path = set(self.path) - yield - self.path = path - - def __str__(self): - state = ( - "%s=%s" - % (field, pprint.pformat(getattr(self, field), width=80 - len(field))) - for field in self.__slots__ - ) - return "%s(%s)" % (type(self).__name__, ",\n ".join(state)) - - -class CallContext: - """Holds information for a call site.""" - - __slots__ = ("args", "keywords") - - def __init__(self, args, keywords=None): - """ - :param List[NodeNG] args: Call positional arguments - :param Union[List[nodes.Keyword], None] keywords: Call keywords - """ - self.args = args - if keywords: - keywords = [(arg.arg, arg.value) for arg in keywords] - else: - keywords = [] - self.keywords = keywords - - -def copy_context(context: Optional[InferenceContext]) -> InferenceContext: - """Clone a context if given, or return a fresh contexxt""" - if context is not None: - return context.clone() - - return InferenceContext() - - -def bind_context_to_node(context, node): - """Give a context a boundnode - to retrieve the correct function name or attribute value - with from further inference. - - Do not use an existing context since the boundnode could then - be incorrectly propagated higher up in the call stack. - - :param context: Context to use - :type context: Optional(context) - - :param node: Node to do name lookups from - :type node NodeNG: - - :returns: A new context - :rtype: InferenceContext - """ - context = copy_context(context) - context.boundnode = node - return context diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/decorators.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/decorators.py deleted file mode 100644 index 0f3632c..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/decorators.py +++ /dev/null @@ -1,142 +0,0 @@ -# Copyright (c) 2015-2016, 2018 Claudiu Popa -# Copyright (c) 2015-2016 Ceridwen -# Copyright (c) 2015 Florian Bruhin -# Copyright (c) 2016 Derek Gustafson -# Copyright (c) 2018 Nick Drozd -# Copyright (c) 2018 Tomas Gavenciak -# Copyright (c) 2018 Ashley Whetter -# Copyright (c) 2018 HoverHell -# Copyright (c) 2018 Bryce Guinta - -# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html -# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER - -""" A few useful function/method decorators.""" - -import functools - -import wrapt - -from astroid import context as contextmod -from astroid import exceptions -from astroid import util - - -@wrapt.decorator -def cached(func, instance, args, kwargs): - """Simple decorator to cache result of method calls without args.""" - cache = getattr(instance, "__cache", None) - if cache is None: - instance.__cache = cache = {} - try: - return cache[func] - except KeyError: - cache[func] = result = func(*args, **kwargs) - return result - - -class cachedproperty: - """ Provides a cached property equivalent to the stacking of - @cached and @property, but more efficient. - - After first usage, the becomes part of the object's - __dict__. Doing: - - del obj. empties the cache. - - Idea taken from the pyramid_ framework and the mercurial_ project. - - .. _pyramid: http://pypi.python.org/pypi/pyramid - .. _mercurial: http://pypi.python.org/pypi/Mercurial - """ - - __slots__ = ("wrapped",) - - def __init__(self, wrapped): - try: - wrapped.__name__ - except AttributeError as exc: - raise TypeError("%s must have a __name__ attribute" % wrapped) from exc - self.wrapped = wrapped - - @property - def __doc__(self): - doc = getattr(self.wrapped, "__doc__", None) - return "%s" % ( - "\n%s" % doc if doc else "" - ) - - def __get__(self, inst, objtype=None): - if inst is None: - return self - val = self.wrapped(inst) - setattr(inst, self.wrapped.__name__, val) - return val - - -def path_wrapper(func): - """return the given infer function wrapped to handle the path - - Used to stop inference if the node has already been looked - at for a given `InferenceContext` to prevent infinite recursion - """ - - @functools.wraps(func) - def wrapped(node, context=None, _func=func, **kwargs): - """wrapper function handling context""" - if context is None: - context = contextmod.InferenceContext() - if context.push(node): - return None - - yielded = set() - generator = _func(node, context, **kwargs) - try: - while True: - res = next(generator) - # unproxy only true instance, not const, tuple, dict... - if res.__class__.__name__ == "Instance": - ares = res._proxied - else: - ares = res - if ares not in yielded: - yield res - yielded.add(ares) - except StopIteration as error: - if error.args: - return error.args[0] - return None - - return wrapped - - -@wrapt.decorator -def yes_if_nothing_inferred(func, instance, args, kwargs): - generator = func(*args, **kwargs) - - try: - yield next(generator) - except StopIteration: - # generator is empty - yield util.Uninferable - return - - yield from generator - - -@wrapt.decorator -def raise_if_nothing_inferred(func, instance, args, kwargs): - generator = func(*args, **kwargs) - - try: - yield next(generator) - except StopIteration as error: - # generator is empty - if error.args: - # pylint: disable=not-a-mapping - raise exceptions.InferenceError(**error.args[0]) - raise exceptions.InferenceError( - "StopIteration raised without any error information." - ) - - yield from generator diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/exceptions.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/exceptions.py deleted file mode 100644 index 08e72c1..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/exceptions.py +++ /dev/null @@ -1,230 +0,0 @@ -# Copyright (c) 2007, 2009-2010, 2013 LOGILAB S.A. (Paris, FRANCE) -# Copyright (c) 2014 Google, Inc. -# Copyright (c) 2015-2018 Claudiu Popa -# Copyright (c) 2015-2016 Ceridwen -# Copyright (c) 2016 Derek Gustafson -# Copyright (c) 2018 Bryce Guinta - -# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html -# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER - -"""this module contains exceptions used in the astroid library -""" -from astroid import util - - -class AstroidError(Exception): - """base exception class for all astroid related exceptions - - AstroidError and its subclasses are structured, intended to hold - objects representing state when the exception is thrown. Field - values are passed to the constructor as keyword-only arguments. - Each subclass has its own set of standard fields, but use your - best judgment to decide whether a specific exception instance - needs more or fewer fields for debugging. Field values may be - used to lazily generate the error message: self.message.format() - will be called with the field names and values supplied as keyword - arguments. - """ - - def __init__(self, message="", **kws): - super().__init__(message) - self.message = message - for key, value in kws.items(): - setattr(self, key, value) - - def __str__(self): - return self.message.format(**vars(self)) - - -class AstroidBuildingError(AstroidError): - """exception class when we are unable to build an astroid representation - - Standard attributes: - modname: Name of the module that AST construction failed for. - error: Exception raised during construction. - """ - - def __init__(self, message="Failed to import module {modname}.", **kws): - super().__init__(message, **kws) - - -class AstroidImportError(AstroidBuildingError): - """Exception class used when a module can't be imported by astroid.""" - - -class TooManyLevelsError(AstroidImportError): - """Exception class which is raised when a relative import was beyond the top-level. - - Standard attributes: - level: The level which was attempted. - name: the name of the module on which the relative import was attempted. - """ - - level = None - name = None - - def __init__( - self, - message="Relative import with too many levels " "({level}) for module {name!r}", - **kws - ): - super().__init__(message, **kws) - - -class AstroidSyntaxError(AstroidBuildingError): - """Exception class used when a module can't be parsed.""" - - -class NoDefault(AstroidError): - """raised by function's `default_value` method when an argument has - no default value - - Standard attributes: - func: Function node. - name: Name of argument without a default. - """ - - func = None - name = None - - def __init__(self, message="{func!r} has no default for {name!r}.", **kws): - super().__init__(message, **kws) - - -class ResolveError(AstroidError): - """Base class of astroid resolution/inference error. - - ResolveError is not intended to be raised. - - Standard attributes: - context: InferenceContext object. - """ - - context = None - - -class MroError(ResolveError): - """Error raised when there is a problem with method resolution of a class. - - Standard attributes: - mros: A sequence of sequences containing ClassDef nodes. - cls: ClassDef node whose MRO resolution failed. - context: InferenceContext object. - """ - - mros = () - cls = None - - def __str__(self): - mro_names = ", ".join( - "({})".format(", ".join(b.name for b in m)) for m in self.mros - ) - return self.message.format(mros=mro_names, cls=self.cls) - - -class DuplicateBasesError(MroError): - """Error raised when there are duplicate bases in the same class bases.""" - - -class InconsistentMroError(MroError): - """Error raised when a class's MRO is inconsistent.""" - - -class SuperError(ResolveError): - """Error raised when there is a problem with a *super* call. - - Standard attributes: - *super_*: The Super instance that raised the exception. - context: InferenceContext object. - """ - - super_ = None - - def __str__(self): - return self.message.format(**vars(self.super_)) - - -class InferenceError(ResolveError): - """raised when we are unable to infer a node - - Standard attributes: - node: The node inference was called on. - context: InferenceContext object. - """ - - node = None - context = None - - def __init__(self, message="Inference failed for {node!r}.", **kws): - super().__init__(message, **kws) - - -# Why does this inherit from InferenceError rather than ResolveError? -# Changing it causes some inference tests to fail. -class NameInferenceError(InferenceError): - """Raised when a name lookup fails, corresponds to NameError. - - Standard attributes: - name: The name for which lookup failed, as a string. - scope: The node representing the scope in which the lookup occurred. - context: InferenceContext object. - """ - - name = None - scope = None - - def __init__(self, message="{name!r} not found in {scope!r}.", **kws): - super().__init__(message, **kws) - - -class AttributeInferenceError(ResolveError): - """Raised when an attribute lookup fails, corresponds to AttributeError. - - Standard attributes: - target: The node for which lookup failed. - attribute: The attribute for which lookup failed, as a string. - context: InferenceContext object. - """ - - target = None - attribute = None - - def __init__(self, message="{attribute!r} not found on {target!r}.", **kws): - super().__init__(message, **kws) - - -class UseInferenceDefault(Exception): - """exception to be raised in custom inference function to indicate that it - should go back to the default behaviour - """ - - -class _NonDeducibleTypeHierarchy(Exception): - """Raised when is_subtype / is_supertype can't deduce the relation between two types.""" - - -class AstroidIndexError(AstroidError): - """Raised when an Indexable / Mapping does not have an index / key.""" - - -class AstroidTypeError(AstroidError): - """Raised when a TypeError would be expected in Python code.""" - - -class InferenceOverwriteError(AstroidError): - """Raised when an inference tip is overwritten - - Currently only used for debugging. - """ - - -# Backwards-compatibility aliases -OperationError = util.BadOperationMessage -UnaryOperationError = util.BadUnaryOperationMessage -BinaryOperationError = util.BadBinaryOperationMessage - -SuperArgumentTypeError = SuperError -UnresolvableName = NameInferenceError -NotFoundError = AttributeInferenceError -AstroidBuildingException = AstroidBuildingError diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/helpers.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/helpers.py deleted file mode 100644 index 1c84651..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/helpers.py +++ /dev/null @@ -1,282 +0,0 @@ -# Copyright (c) 2015-2020 Claudiu Popa -# Copyright (c) 2015-2016 Ceridwen -# Copyright (c) 2018 Bryce Guinta - -# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html -# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER - - -""" -Various helper utilities. -""" - -import builtins as builtins_mod - -from astroid import bases -from astroid import context as contextmod -from astroid import exceptions -from astroid import manager -from astroid import nodes -from astroid import raw_building -from astroid import scoped_nodes -from astroid import util - - -BUILTINS = builtins_mod.__name__ - - -def _build_proxy_class(cls_name, builtins): - proxy = raw_building.build_class(cls_name) - proxy.parent = builtins - return proxy - - -def _function_type(function, builtins): - if isinstance(function, scoped_nodes.Lambda): - if function.root().name == BUILTINS: - cls_name = "builtin_function_or_method" - else: - cls_name = "function" - elif isinstance(function, bases.BoundMethod): - cls_name = "method" - elif isinstance(function, bases.UnboundMethod): - cls_name = "function" - return _build_proxy_class(cls_name, builtins) - - -def _object_type(node, context=None): - astroid_manager = manager.AstroidManager() - builtins = astroid_manager.builtins_module - context = context or contextmod.InferenceContext() - - for inferred in node.infer(context=context): - if isinstance(inferred, scoped_nodes.ClassDef): - if inferred.newstyle: - metaclass = inferred.metaclass(context=context) - if metaclass: - yield metaclass - continue - yield builtins.getattr("type")[0] - elif isinstance(inferred, (scoped_nodes.Lambda, bases.UnboundMethod)): - yield _function_type(inferred, builtins) - elif isinstance(inferred, scoped_nodes.Module): - yield _build_proxy_class("module", builtins) - else: - yield inferred._proxied - - -def object_type(node, context=None): - """Obtain the type of the given node - - This is used to implement the ``type`` builtin, which means that it's - used for inferring type calls, as well as used in a couple of other places - in the inference. - The node will be inferred first, so this function can support all - sorts of objects, as long as they support inference. - """ - - try: - types = set(_object_type(node, context)) - except exceptions.InferenceError: - return util.Uninferable - if len(types) > 1 or not types: - return util.Uninferable - return list(types)[0] - - -def _object_type_is_subclass(obj_type, class_or_seq, context=None): - if not isinstance(class_or_seq, (tuple, list)): - class_seq = (class_or_seq,) - else: - class_seq = class_or_seq - - if obj_type is util.Uninferable: - return util.Uninferable - - # Instances are not types - class_seq = [ - item if not isinstance(item, bases.Instance) else util.Uninferable - for item in class_seq - ] - # strict compatibility with issubclass - # issubclass(type, (object, 1)) evaluates to true - # issubclass(object, (1, type)) raises TypeError - for klass in class_seq: - if klass is util.Uninferable: - raise exceptions.AstroidTypeError("arg 2 must be a type or tuple of types") - - for obj_subclass in obj_type.mro(): - if obj_subclass == klass: - return True - return False - - -def object_isinstance(node, class_or_seq, context=None): - """Check if a node 'isinstance' any node in class_or_seq - - :param node: A given node - :param class_or_seq: Union[nodes.NodeNG, Sequence[nodes.NodeNG]] - :rtype: bool - - :raises AstroidTypeError: if the given ``classes_or_seq`` are not types - """ - obj_type = object_type(node, context) - if obj_type is util.Uninferable: - return util.Uninferable - return _object_type_is_subclass(obj_type, class_or_seq, context=context) - - -def object_issubclass(node, class_or_seq, context=None): - """Check if a type is a subclass of any node in class_or_seq - - :param node: A given node - :param class_or_seq: Union[Nodes.NodeNG, Sequence[nodes.NodeNG]] - :rtype: bool - - :raises AstroidTypeError: if the given ``classes_or_seq`` are not types - :raises AstroidError: if the type of the given node cannot be inferred - or its type's mro doesn't work - """ - if not isinstance(node, nodes.ClassDef): - raise TypeError("{node} needs to be a ClassDef node".format(node=node)) - return _object_type_is_subclass(node, class_or_seq, context=context) - - -def safe_infer(node, context=None): - """Return the inferred value for the given node. - - Return None if inference failed or if there is some ambiguity (more than - one node has been inferred). - """ - try: - inferit = node.infer(context=context) - value = next(inferit) - except exceptions.InferenceError: - return None - try: - next(inferit) - return None # None if there is ambiguity on the inferred node - except exceptions.InferenceError: - return None # there is some kind of ambiguity - except StopIteration: - return value - - -def has_known_bases(klass, context=None): - """Return true if all base classes of a class could be inferred.""" - try: - return klass._all_bases_known - except AttributeError: - pass - for base in klass.bases: - result = safe_infer(base, context=context) - # TODO: check for A->B->A->B pattern in class structure too? - if ( - not isinstance(result, scoped_nodes.ClassDef) - or result is klass - or not has_known_bases(result, context=context) - ): - klass._all_bases_known = False - return False - klass._all_bases_known = True - return True - - -def _type_check(type1, type2): - if not all(map(has_known_bases, (type1, type2))): - raise exceptions._NonDeducibleTypeHierarchy - - if not all([type1.newstyle, type2.newstyle]): - return False - try: - return type1 in type2.mro()[:-1] - except exceptions.MroError: - # The MRO is invalid. - raise exceptions._NonDeducibleTypeHierarchy - - -def is_subtype(type1, type2): - """Check if *type1* is a subtype of *type2*.""" - return _type_check(type1=type2, type2=type1) - - -def is_supertype(type1, type2): - """Check if *type2* is a supertype of *type1*.""" - return _type_check(type1, type2) - - -def class_instance_as_index(node): - """Get the value as an index for the given instance. - - If an instance provides an __index__ method, then it can - be used in some scenarios where an integer is expected, - for instance when multiplying or subscripting a list. - """ - context = contextmod.InferenceContext() - context.callcontext = contextmod.CallContext(args=[node]) - - try: - for inferred in node.igetattr("__index__", context=context): - if not isinstance(inferred, bases.BoundMethod): - continue - - for result in inferred.infer_call_result(node, context=context): - if isinstance(result, nodes.Const) and isinstance(result.value, int): - return result - except exceptions.InferenceError: - pass - return None - - -def object_len(node, context=None): - """Infer length of given node object - - :param Union[nodes.ClassDef, nodes.Instance] node: - :param node: Node to infer length of - - :raises AstroidTypeError: If an invalid node is returned - from __len__ method or no __len__ method exists - :raises InferenceError: If the given node cannot be inferred - or if multiple nodes are inferred - :rtype int: Integer length of node - """ - # pylint: disable=import-outside-toplevel; circular import - from astroid.objects import FrozenSet - - inferred_node = safe_infer(node, context=context) - if inferred_node is None or inferred_node is util.Uninferable: - raise exceptions.InferenceError(node=node) - if isinstance(inferred_node, nodes.Const) and isinstance( - inferred_node.value, (bytes, str) - ): - return len(inferred_node.value) - if isinstance(inferred_node, (nodes.List, nodes.Set, nodes.Tuple, FrozenSet)): - return len(inferred_node.elts) - if isinstance(inferred_node, nodes.Dict): - return len(inferred_node.items) - - node_type = object_type(inferred_node, context=context) - if not node_type: - raise exceptions.InferenceError(node=node) - - try: - len_call = next(node_type.igetattr("__len__", context=context)) - except exceptions.AttributeInferenceError: - raise exceptions.AstroidTypeError( - "object of type '{}' has no len()".format(node_type.pytype()) - ) - - result_of_len = next(len_call.infer_call_result(node, context)) - if ( - isinstance(result_of_len, nodes.Const) - and result_of_len.pytype() == "builtins.int" - ): - return result_of_len.value - if isinstance(result_of_len, bases.Instance) and result_of_len.is_subtype_of( - "builtins.int" - ): - # Fake a result as we don't know the arguments of the instance call. - return 0 - raise exceptions.AstroidTypeError( - "'{}' object cannot be interpreted as an integer".format(result_of_len) - ) diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/inference.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/inference.py deleted file mode 100644 index bc3e1f9..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/inference.py +++ /dev/null @@ -1,994 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright (c) 2006-2011, 2013-2014 LOGILAB S.A. (Paris, FRANCE) -# Copyright (c) 2012 FELD Boris -# Copyright (c) 2013-2014 Google, Inc. -# Copyright (c) 2014-2020 Claudiu Popa -# Copyright (c) 2014 Eevee (Alex Munroe) -# Copyright (c) 2015-2016 Ceridwen -# Copyright (c) 2015 Dmitry Pribysh -# Copyright (c) 2016 Jakub Wilk -# Copyright (c) 2017 Michał Masłowski -# Copyright (c) 2017 Calen Pennington -# Copyright (c) 2017 Łukasz Rogalski -# Copyright (c) 2018-2019 Nick Drozd -# Copyright (c) 2018 Daniel Martin -# Copyright (c) 2018 Ville Skyttä -# Copyright (c) 2018 Bryce Guinta -# Copyright (c) 2018 Ashley Whetter -# Copyright (c) 2018 HoverHell -# Copyright (c) 2020 Leandro T. C. Melo - -# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html -# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER - -"""this module contains a set of functions to handle inference on astroid trees -""" - -import functools -import itertools -import operator - -import wrapt -from astroid import bases -from astroid import context as contextmod -from astroid import exceptions -from astroid import decorators -from astroid import helpers -from astroid import manager -from astroid import nodes -from astroid.interpreter import dunder_lookup -from astroid import protocols -from astroid import util - - -MANAGER = manager.AstroidManager() -# Prevents circular imports -objects = util.lazy_import("objects") - - -# .infer method ############################################################### - - -def infer_end(self, context=None): - """Inference's end for nodes that yield themselves on inference - - These are objects for which inference does not have any semantic, - such as Module or Consts. - """ - yield self - - -nodes.Module._infer = infer_end -nodes.ClassDef._infer = infer_end -nodes.Lambda._infer = infer_end -nodes.Const._infer = infer_end -nodes.Slice._infer = infer_end - - -def _infer_sequence_helper(node, context=None): - """Infer all values based on _BaseContainer.elts""" - values = [] - - for elt in node.elts: - if isinstance(elt, nodes.Starred): - starred = helpers.safe_infer(elt.value, context) - if not starred: - raise exceptions.InferenceError(node=node, context=context) - if not hasattr(starred, "elts"): - raise exceptions.InferenceError(node=node, context=context) - values.extend(_infer_sequence_helper(starred)) - elif isinstance(elt, nodes.NamedExpr): - value = helpers.safe_infer(elt.value, context) - if not value: - raise exceptions.InferenceError(node=node, context=context) - values.append(value) - else: - values.append(elt) - return values - - -@decorators.raise_if_nothing_inferred -def infer_sequence(self, context=None): - has_starred_named_expr = any( - isinstance(e, (nodes.Starred, nodes.NamedExpr)) for e in self.elts - ) - if has_starred_named_expr: - values = _infer_sequence_helper(self, context) - new_seq = type(self)( - lineno=self.lineno, col_offset=self.col_offset, parent=self.parent - ) - new_seq.postinit(values) - - yield new_seq - else: - yield self - - -nodes.List._infer = infer_sequence -nodes.Tuple._infer = infer_sequence -nodes.Set._infer = infer_sequence - - -def infer_map(self, context=None): - if not any(isinstance(k, nodes.DictUnpack) for k, _ in self.items): - yield self - else: - items = _infer_map(self, context) - new_seq = type(self)(self.lineno, self.col_offset, self.parent) - new_seq.postinit(list(items.items())) - yield new_seq - - -def _update_with_replacement(lhs_dict, rhs_dict): - """Delete nodes that equate to duplicate keys - - Since an astroid node doesn't 'equal' another node with the same value, - this function uses the as_string method to make sure duplicate keys - don't get through - - Note that both the key and the value are astroid nodes - - Fixes issue with DictUnpack causing duplicte keys - in inferred Dict items - - :param dict(nodes.NodeNG, nodes.NodeNG) lhs_dict: Dictionary to 'merge' nodes into - :param dict(nodes.NodeNG, nodes.NodeNG) rhs_dict: Dictionary with nodes to pull from - :return dict(nodes.NodeNG, nodes.NodeNG): merged dictionary of nodes - """ - combined_dict = itertools.chain(lhs_dict.items(), rhs_dict.items()) - # Overwrite keys which have the same string values - string_map = {key.as_string(): (key, value) for key, value in combined_dict} - # Return to dictionary - return dict(string_map.values()) - - -def _infer_map(node, context): - """Infer all values based on Dict.items""" - values = {} - for name, value in node.items: - if isinstance(name, nodes.DictUnpack): - double_starred = helpers.safe_infer(value, context) - if not double_starred: - raise exceptions.InferenceError - if not isinstance(double_starred, nodes.Dict): - raise exceptions.InferenceError(node=node, context=context) - unpack_items = _infer_map(double_starred, context) - values = _update_with_replacement(values, unpack_items) - else: - key = helpers.safe_infer(name, context=context) - value = helpers.safe_infer(value, context=context) - if any(not elem for elem in (key, value)): - raise exceptions.InferenceError(node=node, context=context) - values = _update_with_replacement(values, {key: value}) - return values - - -nodes.Dict._infer = infer_map - - -def _higher_function_scope(node): - """ Search for the first function which encloses the given - scope. This can be used for looking up in that function's - scope, in case looking up in a lower scope for a particular - name fails. - - :param node: A scope node. - :returns: - ``None``, if no parent function scope was found, - otherwise an instance of :class:`astroid.scoped_nodes.Function`, - which encloses the given node. - """ - current = node - while current.parent and not isinstance(current.parent, nodes.FunctionDef): - current = current.parent - if current and current.parent: - return current.parent - return None - - -def infer_name(self, context=None): - """infer a Name: use name lookup rules""" - frame, stmts = self.lookup(self.name) - if not stmts: - # Try to see if the name is enclosed in a nested function - # and use the higher (first function) scope for searching. - parent_function = _higher_function_scope(self.scope()) - if parent_function: - _, stmts = parent_function.lookup(self.name) - - if not stmts: - raise exceptions.NameInferenceError( - name=self.name, scope=self.scope(), context=context - ) - context = contextmod.copy_context(context) - context.lookupname = self.name - return bases._infer_stmts(stmts, context, frame) - - -# pylint: disable=no-value-for-parameter -nodes.Name._infer = decorators.raise_if_nothing_inferred( - decorators.path_wrapper(infer_name) -) -nodes.AssignName.infer_lhs = infer_name # won't work with a path wrapper - - -@decorators.raise_if_nothing_inferred -@decorators.path_wrapper -def infer_call(self, context=None): - """infer a Call node by trying to guess what the function returns""" - callcontext = contextmod.copy_context(context) - callcontext.callcontext = contextmod.CallContext( - args=self.args, keywords=self.keywords - ) - callcontext.boundnode = None - if context is not None: - callcontext.extra_context = _populate_context_lookup(self, context.clone()) - - for callee in self.func.infer(context): - if callee is util.Uninferable: - yield callee - continue - try: - if hasattr(callee, "infer_call_result"): - yield from callee.infer_call_result(caller=self, context=callcontext) - except exceptions.InferenceError: - continue - return dict(node=self, context=context) - - -nodes.Call._infer = infer_call - - -@decorators.raise_if_nothing_inferred -@decorators.path_wrapper -def infer_import(self, context=None, asname=True): - """infer an Import node: return the imported module/object""" - name = context.lookupname - if name is None: - raise exceptions.InferenceError(node=self, context=context) - - try: - if asname: - yield self.do_import_module(self.real_name(name)) - else: - yield self.do_import_module(name) - except exceptions.AstroidBuildingError as exc: - raise exceptions.InferenceError(node=self, context=context) from exc - - -nodes.Import._infer = infer_import - - -@decorators.raise_if_nothing_inferred -@decorators.path_wrapper -def infer_import_from(self, context=None, asname=True): - """infer a ImportFrom node: return the imported module/object""" - name = context.lookupname - if name is None: - raise exceptions.InferenceError(node=self, context=context) - if asname: - name = self.real_name(name) - - try: - module = self.do_import_module() - except exceptions.AstroidBuildingError as exc: - raise exceptions.InferenceError(node=self, context=context) from exc - - try: - context = contextmod.copy_context(context) - context.lookupname = name - stmts = module.getattr(name, ignore_locals=module is self.root()) - return bases._infer_stmts(stmts, context) - except exceptions.AttributeInferenceError as error: - raise exceptions.InferenceError( - error.message, target=self, attribute=name, context=context - ) from error - - -nodes.ImportFrom._infer = infer_import_from - - -def infer_attribute(self, context=None): - """infer an Attribute node by using getattr on the associated object""" - for owner in self.expr.infer(context): - if owner is util.Uninferable: - yield owner - continue - - if context and context.boundnode: - # This handles the situation where the attribute is accessed through a subclass - # of a base class and the attribute is defined at the base class's level, - # by taking in consideration a redefinition in the subclass. - if isinstance(owner, bases.Instance) and isinstance( - context.boundnode, bases.Instance - ): - try: - if helpers.is_subtype( - helpers.object_type(context.boundnode), - helpers.object_type(owner), - ): - owner = context.boundnode - except exceptions._NonDeducibleTypeHierarchy: - # Can't determine anything useful. - pass - elif not context: - context = contextmod.InferenceContext() - - try: - context.boundnode = owner - yield from owner.igetattr(self.attrname, context) - except ( - exceptions.AttributeInferenceError, - exceptions.InferenceError, - AttributeError, - ): - pass - finally: - context.boundnode = None - return dict(node=self, context=context) - - -nodes.Attribute._infer = decorators.raise_if_nothing_inferred( - decorators.path_wrapper(infer_attribute) -) -# won't work with a path wrapper -nodes.AssignAttr.infer_lhs = decorators.raise_if_nothing_inferred(infer_attribute) - - -@decorators.raise_if_nothing_inferred -@decorators.path_wrapper -def infer_global(self, context=None): - if context.lookupname is None: - raise exceptions.InferenceError(node=self, context=context) - try: - return bases._infer_stmts(self.root().getattr(context.lookupname), context) - except exceptions.AttributeInferenceError as error: - raise exceptions.InferenceError( - error.message, target=self, attribute=context.lookupname, context=context - ) from error - - -nodes.Global._infer = infer_global - - -_SUBSCRIPT_SENTINEL = object() - - -def infer_subscript(self, context=None): - """Inference for subscripts - - We're understanding if the index is a Const - or a slice, passing the result of inference - to the value's `getitem` method, which should - handle each supported index type accordingly. - """ - - found_one = False - for value in self.value.infer(context): - if value is util.Uninferable: - yield util.Uninferable - return None - for index in self.slice.infer(context): - if index is util.Uninferable: - yield util.Uninferable - return None - - # Try to deduce the index value. - index_value = _SUBSCRIPT_SENTINEL - if value.__class__ == bases.Instance: - index_value = index - elif index.__class__ == bases.Instance: - instance_as_index = helpers.class_instance_as_index(index) - if instance_as_index: - index_value = instance_as_index - else: - index_value = index - - if index_value is _SUBSCRIPT_SENTINEL: - raise exceptions.InferenceError(node=self, context=context) - - try: - assigned = value.getitem(index_value, context) - except ( - exceptions.AstroidTypeError, - exceptions.AstroidIndexError, - exceptions.AttributeInferenceError, - AttributeError, - ) as exc: - raise exceptions.InferenceError(node=self, context=context) from exc - - # Prevent inferring if the inferred subscript - # is the same as the original subscripted object. - if self is assigned or assigned is util.Uninferable: - yield util.Uninferable - return None - yield from assigned.infer(context) - found_one = True - - if found_one: - return dict(node=self, context=context) - return None - - -nodes.Subscript._infer = decorators.raise_if_nothing_inferred( - decorators.path_wrapper(infer_subscript) -) -nodes.Subscript.infer_lhs = decorators.raise_if_nothing_inferred(infer_subscript) - - -@decorators.raise_if_nothing_inferred -@decorators.path_wrapper -def _infer_boolop(self, context=None): - """Infer a boolean operation (and / or / not). - - The function will calculate the boolean operation - for all pairs generated through inference for each component - node. - """ - values = self.values - if self.op == "or": - predicate = operator.truth - else: - predicate = operator.not_ - - try: - values = [value.infer(context=context) for value in values] - except exceptions.InferenceError: - yield util.Uninferable - return None - - for pair in itertools.product(*values): - if any(item is util.Uninferable for item in pair): - # Can't infer the final result, just yield Uninferable. - yield util.Uninferable - continue - - bool_values = [item.bool_value() for item in pair] - if any(item is util.Uninferable for item in bool_values): - # Can't infer the final result, just yield Uninferable. - yield util.Uninferable - continue - - # Since the boolean operations are short circuited operations, - # this code yields the first value for which the predicate is True - # and if no value respected the predicate, then the last value will - # be returned (or Uninferable if there was no last value). - # This is conforming to the semantics of `and` and `or`: - # 1 and 0 -> 1 - # 0 and 1 -> 0 - # 1 or 0 -> 1 - # 0 or 1 -> 1 - value = util.Uninferable - for value, bool_value in zip(pair, bool_values): - if predicate(bool_value): - yield value - break - else: - yield value - - return dict(node=self, context=context) - - -nodes.BoolOp._infer = _infer_boolop - - -# UnaryOp, BinOp and AugAssign inferences - - -def _filter_operation_errors(self, infer_callable, context, error): - for result in infer_callable(self, context): - if isinstance(result, error): - # For the sake of .infer(), we don't care about operation - # errors, which is the job of pylint. So return something - # which shows that we can't infer the result. - yield util.Uninferable - else: - yield result - - -def _infer_unaryop(self, context=None): - """Infer what an UnaryOp should return when evaluated.""" - for operand in self.operand.infer(context): - try: - yield operand.infer_unary_op(self.op) - except TypeError as exc: - # The operand doesn't support this operation. - yield util.BadUnaryOperationMessage(operand, self.op, exc) - except AttributeError as exc: - meth = protocols.UNARY_OP_METHOD[self.op] - if meth is None: - # `not node`. Determine node's boolean - # value and negate its result, unless it is - # Uninferable, which will be returned as is. - bool_value = operand.bool_value() - if bool_value is not util.Uninferable: - yield nodes.const_factory(not bool_value) - else: - yield util.Uninferable - else: - if not isinstance(operand, (bases.Instance, nodes.ClassDef)): - # The operation was used on something which - # doesn't support it. - yield util.BadUnaryOperationMessage(operand, self.op, exc) - continue - - try: - try: - methods = dunder_lookup.lookup(operand, meth) - except exceptions.AttributeInferenceError: - yield util.BadUnaryOperationMessage(operand, self.op, exc) - continue - - meth = methods[0] - inferred = next(meth.infer(context=context)) - if inferred is util.Uninferable or not inferred.callable(): - continue - - context = contextmod.copy_context(context) - context.callcontext = contextmod.CallContext(args=[operand]) - call_results = inferred.infer_call_result(self, context=context) - result = next(call_results, None) - if result is None: - # Failed to infer, return the same type. - yield operand - else: - yield result - except exceptions.AttributeInferenceError as exc: - # The unary operation special method was not found. - yield util.BadUnaryOperationMessage(operand, self.op, exc) - except exceptions.InferenceError: - yield util.Uninferable - - -@decorators.raise_if_nothing_inferred -@decorators.path_wrapper -def infer_unaryop(self, context=None): - """Infer what an UnaryOp should return when evaluated.""" - yield from _filter_operation_errors( - self, _infer_unaryop, context, util.BadUnaryOperationMessage - ) - return dict(node=self, context=context) - - -nodes.UnaryOp._infer_unaryop = _infer_unaryop -nodes.UnaryOp._infer = infer_unaryop - - -def _is_not_implemented(const): - """Check if the given const node is NotImplemented.""" - return isinstance(const, nodes.Const) and const.value is NotImplemented - - -def _invoke_binop_inference(instance, opnode, op, other, context, method_name): - """Invoke binary operation inference on the given instance.""" - methods = dunder_lookup.lookup(instance, method_name) - context = contextmod.bind_context_to_node(context, instance) - method = methods[0] - inferred = next(method.infer(context=context)) - if inferred is util.Uninferable: - raise exceptions.InferenceError - return instance.infer_binary_op(opnode, op, other, context, inferred) - - -def _aug_op(instance, opnode, op, other, context, reverse=False): - """Get an inference callable for an augmented binary operation.""" - method_name = protocols.AUGMENTED_OP_METHOD[op] - return functools.partial( - _invoke_binop_inference, - instance=instance, - op=op, - opnode=opnode, - other=other, - context=context, - method_name=method_name, - ) - - -def _bin_op(instance, opnode, op, other, context, reverse=False): - """Get an inference callable for a normal binary operation. - - If *reverse* is True, then the reflected method will be used instead. - """ - if reverse: - method_name = protocols.REFLECTED_BIN_OP_METHOD[op] - else: - method_name = protocols.BIN_OP_METHOD[op] - return functools.partial( - _invoke_binop_inference, - instance=instance, - op=op, - opnode=opnode, - other=other, - context=context, - method_name=method_name, - ) - - -def _get_binop_contexts(context, left, right): - """Get contexts for binary operations. - - This will return two inference contexts, the first one - for x.__op__(y), the other one for y.__rop__(x), where - only the arguments are inversed. - """ - # The order is important, since the first one should be - # left.__op__(right). - for arg in (right, left): - new_context = context.clone() - new_context.callcontext = contextmod.CallContext(args=[arg]) - new_context.boundnode = None - yield new_context - - -def _same_type(type1, type2): - """Check if type1 is the same as type2.""" - return type1.qname() == type2.qname() - - -def _get_binop_flow( - left, left_type, binary_opnode, right, right_type, context, reverse_context -): - """Get the flow for binary operations. - - The rules are a bit messy: - - * if left and right have the same type, then only one - method will be called, left.__op__(right) - * if left and right are unrelated typewise, then first - left.__op__(right) is tried and if this does not exist - or returns NotImplemented, then right.__rop__(left) is tried. - * if left is a subtype of right, then only left.__op__(right) - is tried. - * if left is a supertype of right, then right.__rop__(left) - is first tried and then left.__op__(right) - """ - op = binary_opnode.op - if _same_type(left_type, right_type): - methods = [_bin_op(left, binary_opnode, op, right, context)] - elif helpers.is_subtype(left_type, right_type): - methods = [_bin_op(left, binary_opnode, op, right, context)] - elif helpers.is_supertype(left_type, right_type): - methods = [ - _bin_op(right, binary_opnode, op, left, reverse_context, reverse=True), - _bin_op(left, binary_opnode, op, right, context), - ] - else: - methods = [ - _bin_op(left, binary_opnode, op, right, context), - _bin_op(right, binary_opnode, op, left, reverse_context, reverse=True), - ] - return methods - - -def _get_aug_flow( - left, left_type, aug_opnode, right, right_type, context, reverse_context -): - """Get the flow for augmented binary operations. - - The rules are a bit messy: - - * if left and right have the same type, then left.__augop__(right) - is first tried and then left.__op__(right). - * if left and right are unrelated typewise, then - left.__augop__(right) is tried, then left.__op__(right) - is tried and then right.__rop__(left) is tried. - * if left is a subtype of right, then left.__augop__(right) - is tried and then left.__op__(right). - * if left is a supertype of right, then left.__augop__(right) - is tried, then right.__rop__(left) and then - left.__op__(right) - """ - bin_op = aug_opnode.op.strip("=") - aug_op = aug_opnode.op - if _same_type(left_type, right_type): - methods = [ - _aug_op(left, aug_opnode, aug_op, right, context), - _bin_op(left, aug_opnode, bin_op, right, context), - ] - elif helpers.is_subtype(left_type, right_type): - methods = [ - _aug_op(left, aug_opnode, aug_op, right, context), - _bin_op(left, aug_opnode, bin_op, right, context), - ] - elif helpers.is_supertype(left_type, right_type): - methods = [ - _aug_op(left, aug_opnode, aug_op, right, context), - _bin_op(right, aug_opnode, bin_op, left, reverse_context, reverse=True), - _bin_op(left, aug_opnode, bin_op, right, context), - ] - else: - methods = [ - _aug_op(left, aug_opnode, aug_op, right, context), - _bin_op(left, aug_opnode, bin_op, right, context), - _bin_op(right, aug_opnode, bin_op, left, reverse_context, reverse=True), - ] - return methods - - -def _infer_binary_operation(left, right, binary_opnode, context, flow_factory): - """Infer a binary operation between a left operand and a right operand - - This is used by both normal binary operations and augmented binary - operations, the only difference is the flow factory used. - """ - - context, reverse_context = _get_binop_contexts(context, left, right) - left_type = helpers.object_type(left) - right_type = helpers.object_type(right) - methods = flow_factory( - left, left_type, binary_opnode, right, right_type, context, reverse_context - ) - for method in methods: - try: - results = list(method()) - except AttributeError: - continue - except exceptions.AttributeInferenceError: - continue - except exceptions.InferenceError: - yield util.Uninferable - return - else: - if any(result is util.Uninferable for result in results): - yield util.Uninferable - return - - if all(map(_is_not_implemented, results)): - continue - not_implemented = sum( - 1 for result in results if _is_not_implemented(result) - ) - if not_implemented and not_implemented != len(results): - # Can't infer yet what this is. - yield util.Uninferable - return - - yield from results - return - # The operation doesn't seem to be supported so let the caller know about it - yield util.BadBinaryOperationMessage(left_type, binary_opnode.op, right_type) - - -def _infer_binop(self, context): - """Binary operation inference logic.""" - left = self.left - right = self.right - - # we use two separate contexts for evaluating lhs and rhs because - # 1. evaluating lhs may leave some undesired entries in context.path - # which may not let us infer right value of rhs - context = context or contextmod.InferenceContext() - lhs_context = contextmod.copy_context(context) - rhs_context = contextmod.copy_context(context) - lhs_iter = left.infer(context=lhs_context) - rhs_iter = right.infer(context=rhs_context) - for lhs, rhs in itertools.product(lhs_iter, rhs_iter): - if any(value is util.Uninferable for value in (rhs, lhs)): - # Don't know how to process this. - yield util.Uninferable - return - - try: - yield from _infer_binary_operation(lhs, rhs, self, context, _get_binop_flow) - except exceptions._NonDeducibleTypeHierarchy: - yield util.Uninferable - - -@decorators.yes_if_nothing_inferred -@decorators.path_wrapper -def infer_binop(self, context=None): - return _filter_operation_errors( - self, _infer_binop, context, util.BadBinaryOperationMessage - ) - - -nodes.BinOp._infer_binop = _infer_binop -nodes.BinOp._infer = infer_binop - - -def _infer_augassign(self, context=None): - """Inference logic for augmented binary operations.""" - if context is None: - context = contextmod.InferenceContext() - - rhs_context = context.clone() - - lhs_iter = self.target.infer_lhs(context=context) - rhs_iter = self.value.infer(context=rhs_context) - for lhs, rhs in itertools.product(lhs_iter, rhs_iter): - if any(value is util.Uninferable for value in (rhs, lhs)): - # Don't know how to process this. - yield util.Uninferable - return - - try: - yield from _infer_binary_operation( - left=lhs, - right=rhs, - binary_opnode=self, - context=context, - flow_factory=_get_aug_flow, - ) - except exceptions._NonDeducibleTypeHierarchy: - yield util.Uninferable - - -@decorators.raise_if_nothing_inferred -@decorators.path_wrapper -def infer_augassign(self, context=None): - return _filter_operation_errors( - self, _infer_augassign, context, util.BadBinaryOperationMessage - ) - - -nodes.AugAssign._infer_augassign = _infer_augassign -nodes.AugAssign._infer = infer_augassign - -# End of binary operation inference. - - -@decorators.raise_if_nothing_inferred -def infer_arguments(self, context=None): - name = context.lookupname - if name is None: - raise exceptions.InferenceError(node=self, context=context) - return protocols._arguments_infer_argname(self, name, context) - - -nodes.Arguments._infer = infer_arguments - - -@decorators.raise_if_nothing_inferred -@decorators.path_wrapper -def infer_assign(self, context=None): - """infer a AssignName/AssignAttr: need to inspect the RHS part of the - assign node - """ - if isinstance(self.parent, nodes.AugAssign): - return self.parent.infer(context) - - stmts = list(self.assigned_stmts(context=context)) - return bases._infer_stmts(stmts, context) - - -nodes.AssignName._infer = infer_assign -nodes.AssignAttr._infer = infer_assign - - -@decorators.raise_if_nothing_inferred -@decorators.path_wrapper -def infer_empty_node(self, context=None): - if not self.has_underlying_object(): - yield util.Uninferable - else: - try: - yield from MANAGER.infer_ast_from_something(self.object, context=context) - except exceptions.AstroidError: - yield util.Uninferable - - -nodes.EmptyNode._infer = infer_empty_node - - -@decorators.raise_if_nothing_inferred -def infer_index(self, context=None): - return self.value.infer(context) - - -nodes.Index._infer = infer_index - -# TODO: move directly into bases.Instance when the dependency hell -# will be solved. -def instance_getitem(self, index, context=None): - # Rewrap index to Const for this case - new_context = contextmod.bind_context_to_node(context, self) - if not context: - context = new_context - - # Create a new callcontext for providing index as an argument. - new_context.callcontext = contextmod.CallContext(args=[index]) - - method = next(self.igetattr("__getitem__", context=context), None) - if not isinstance(method, bases.BoundMethod): - raise exceptions.InferenceError( - "Could not find __getitem__ for {node!r}.", node=self, context=context - ) - - return next(method.infer_call_result(self, new_context)) - - -bases.Instance.getitem = instance_getitem - - -def _populate_context_lookup(call, context): - # Allows context to be saved for later - # for inference inside a function - context_lookup = {} - if context is None: - return context_lookup - for arg in call.args: - if isinstance(arg, nodes.Starred): - context_lookup[arg.value] = context - else: - context_lookup[arg] = context - keywords = call.keywords if call.keywords is not None else [] - for keyword in keywords: - context_lookup[keyword.value] = context - return context_lookup - - -@decorators.raise_if_nothing_inferred -def infer_ifexp(self, context=None): - """Support IfExp inference - - If we can't infer the truthiness of the condition, we default - to inferring both branches. Otherwise, we infer either branch - depending on the condition. - """ - both_branches = False - # We use two separate contexts for evaluating lhs and rhs because - # evaluating lhs may leave some undesired entries in context.path - # which may not let us infer right value of rhs. - - context = context or contextmod.InferenceContext() - lhs_context = contextmod.copy_context(context) - rhs_context = contextmod.copy_context(context) - try: - test = next(self.test.infer(context=context.clone())) - except exceptions.InferenceError: - both_branches = True - else: - if test is not util.Uninferable: - if test.bool_value(): - yield from self.body.infer(context=lhs_context) - else: - yield from self.orelse.infer(context=rhs_context) - else: - both_branches = True - if both_branches: - yield from self.body.infer(context=lhs_context) - yield from self.orelse.infer(context=rhs_context) - - -nodes.IfExp._infer = infer_ifexp - - -# pylint: disable=dangerous-default-value -@wrapt.decorator -def _cached_generator(func, instance, args, kwargs, _cache={}): - node = args[0] - try: - return iter(_cache[func, id(node)]) - except KeyError: - result = func(*args, **kwargs) - # Need to keep an iterator around - original, copy = itertools.tee(result) - _cache[func, id(node)] = list(copy) - return original - - -# When inferring a property, we instantiate a new `objects.Property` object, -# which in turn, because it inherits from `FunctionDef`, sets itself in the locals -# of the wrapping frame. This means that everytime we infer a property, the locals -# are mutated with a new instance of the property. This is why we cache the result -# of the function's inference. -@_cached_generator -def infer_functiondef(self, context=None): - if not self.decorators or not bases._is_property(self): - yield self - return dict(node=self, context=context) - - prop_func = objects.Property( - function=self, - name=self.name, - doc=self.doc, - lineno=self.lineno, - parent=self.parent, - col_offset=self.col_offset, - ) - prop_func.postinit(body=[], args=self.args) - yield prop_func - return dict(node=self, context=context) - - -nodes.FunctionDef._infer = infer_functiondef diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/interpreter/__init__.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/interpreter/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/interpreter/__pycache__/__init__.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/interpreter/__pycache__/__init__.cpython-38.pyc deleted file mode 100644 index 8eefa78..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/interpreter/__pycache__/__init__.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/interpreter/__pycache__/dunder_lookup.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/interpreter/__pycache__/dunder_lookup.cpython-38.pyc deleted file mode 100644 index 52ae20a..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/interpreter/__pycache__/dunder_lookup.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/interpreter/__pycache__/objectmodel.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/interpreter/__pycache__/objectmodel.cpython-38.pyc deleted file mode 100644 index 9704e40..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/interpreter/__pycache__/objectmodel.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/interpreter/_import/__init__.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/interpreter/_import/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/interpreter/_import/__pycache__/__init__.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/interpreter/_import/__pycache__/__init__.cpython-38.pyc deleted file mode 100644 index 46eb956..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/interpreter/_import/__pycache__/__init__.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/interpreter/_import/__pycache__/spec.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/interpreter/_import/__pycache__/spec.cpython-38.pyc deleted file mode 100644 index bbfb2bb..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/interpreter/_import/__pycache__/spec.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/interpreter/_import/__pycache__/util.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/interpreter/_import/__pycache__/util.cpython-38.pyc deleted file mode 100644 index 4cbc529..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/interpreter/_import/__pycache__/util.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/interpreter/_import/spec.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/interpreter/_import/spec.py deleted file mode 100644 index 3cf5fea..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/interpreter/_import/spec.py +++ /dev/null @@ -1,346 +0,0 @@ -# Copyright (c) 2016-2018 Claudiu Popa -# Copyright (c) 2016 Derek Gustafson -# Copyright (c) 2017 Chris Philip -# Copyright (c) 2017 Hugo -# Copyright (c) 2017 ioanatia -# Copyright (c) 2017 Calen Pennington -# Copyright (c) 2018 Nick Drozd -# Copyright (c) 2019 Hugo van Kemenade -# Copyright (c) 2019 Ashley Whetter - -import abc -import collections -import distutils -import enum -import imp -import os -import sys -import zipimport - -try: - import importlib.machinery - - _HAS_MACHINERY = True -except ImportError: - _HAS_MACHINERY = False - -try: - from functools import lru_cache -except ImportError: - from backports.functools_lru_cache import lru_cache - -from . import util - -ModuleType = enum.Enum( - "ModuleType", - "C_BUILTIN C_EXTENSION PKG_DIRECTORY " - "PY_CODERESOURCE PY_COMPILED PY_FROZEN PY_RESOURCE " - "PY_SOURCE PY_ZIPMODULE PY_NAMESPACE", -) -_ImpTypes = { - imp.C_BUILTIN: ModuleType.C_BUILTIN, - imp.C_EXTENSION: ModuleType.C_EXTENSION, - imp.PKG_DIRECTORY: ModuleType.PKG_DIRECTORY, - imp.PY_COMPILED: ModuleType.PY_COMPILED, - imp.PY_FROZEN: ModuleType.PY_FROZEN, - imp.PY_SOURCE: ModuleType.PY_SOURCE, -} -if hasattr(imp, "PY_RESOURCE"): - _ImpTypes[imp.PY_RESOURCE] = ModuleType.PY_RESOURCE -if hasattr(imp, "PY_CODERESOURCE"): - _ImpTypes[imp.PY_CODERESOURCE] = ModuleType.PY_CODERESOURCE - - -def _imp_type_to_module_type(imp_type): - return _ImpTypes[imp_type] - - -_ModuleSpec = collections.namedtuple( - "_ModuleSpec", "name type location " "origin submodule_search_locations" -) - - -class ModuleSpec(_ModuleSpec): - """Defines a class similar to PEP 420's ModuleSpec - - A module spec defines a name of a module, its type, location - and where submodules can be found, if the module is a package. - """ - - def __new__( - cls, - name, - module_type, - location=None, - origin=None, - submodule_search_locations=None, - ): - return _ModuleSpec.__new__( - cls, - name=name, - type=module_type, - location=location, - origin=origin, - submodule_search_locations=submodule_search_locations, - ) - - -class Finder: - """A finder is a class which knows how to find a particular module.""" - - def __init__(self, path=None): - self._path = path or sys.path - - @abc.abstractmethod - def find_module(self, modname, module_parts, processed, submodule_path): - """Find the given module - - Each finder is responsible for each protocol of finding, as long as - they all return a ModuleSpec. - - :param str modname: The module which needs to be searched. - :param list module_parts: It should be a list of strings, - where each part contributes to the module's - namespace. - :param list processed: What parts from the module parts were processed - so far. - :param list submodule_path: A list of paths where the module - can be looked into. - :returns: A ModuleSpec, describing how and where the module was found, - None, otherwise. - """ - - def contribute_to_path(self, spec, processed): - """Get a list of extra paths where this finder can search.""" - - -class ImpFinder(Finder): - """A finder based on the imp module.""" - - def find_module(self, modname, module_parts, processed, submodule_path): - if submodule_path is not None: - submodule_path = list(submodule_path) - try: - stream, mp_filename, mp_desc = imp.find_module(modname, submodule_path) - except ImportError: - return None - - # Close resources. - if stream: - stream.close() - - return ModuleSpec( - name=modname, - location=mp_filename, - module_type=_imp_type_to_module_type(mp_desc[2]), - ) - - def contribute_to_path(self, spec, processed): - if spec.location is None: - # Builtin. - return None - - if _is_setuptools_namespace(spec.location): - # extend_path is called, search sys.path for module/packages - # of this name see pkgutil.extend_path documentation - path = [ - os.path.join(p, *processed) - for p in sys.path - if os.path.isdir(os.path.join(p, *processed)) - ] - # We already import distutils elsewhere in astroid, - # so if it is the same module, we can use it directly. - elif spec.name == "distutils" and spec.location in distutils.__path__: - # distutils is patched inside virtualenvs to pick up submodules - # from the original Python, not from the virtualenv itself. - path = list(distutils.__path__) - else: - path = [spec.location] - return path - - -class ExplicitNamespacePackageFinder(ImpFinder): - """A finder for the explicit namespace packages, generated through pkg_resources.""" - - def find_module(self, modname, module_parts, processed, submodule_path): - if processed: - modname = ".".join(processed + [modname]) - if util.is_namespace(modname) and modname in sys.modules: - submodule_path = sys.modules[modname].__path__ - return ModuleSpec( - name=modname, - location="", - origin="namespace", - module_type=ModuleType.PY_NAMESPACE, - submodule_search_locations=submodule_path, - ) - return None - - def contribute_to_path(self, spec, processed): - return spec.submodule_search_locations - - -class ZipFinder(Finder): - """Finder that knows how to find a module inside zip files.""" - - def __init__(self, path): - super().__init__(path) - self._zipimporters = _precache_zipimporters(path) - - def find_module(self, modname, module_parts, processed, submodule_path): - try: - file_type, filename, path = _search_zip(module_parts, self._zipimporters) - except ImportError: - return None - - return ModuleSpec( - name=modname, - location=filename, - origin="egg", - module_type=file_type, - submodule_search_locations=path, - ) - - -class PathSpecFinder(Finder): - """Finder based on importlib.machinery.PathFinder.""" - - def find_module(self, modname, module_parts, processed, submodule_path): - spec = importlib.machinery.PathFinder.find_spec(modname, path=submodule_path) - if spec: - # origin can be either a string on older Python versions - # or None in case it is a namespace package: - # https://github.com/python/cpython/pull/5481 - is_namespace_pkg = spec.origin in ("namespace", None) - location = spec.origin if not is_namespace_pkg else None - module_type = ModuleType.PY_NAMESPACE if is_namespace_pkg else None - spec = ModuleSpec( - name=spec.name, - location=location, - origin=spec.origin, - module_type=module_type, - submodule_search_locations=list(spec.submodule_search_locations or []), - ) - return spec - - def contribute_to_path(self, spec, processed): - if spec.type == ModuleType.PY_NAMESPACE: - return spec.submodule_search_locations - return None - - -_SPEC_FINDERS = (ImpFinder, ZipFinder) -if _HAS_MACHINERY: - _SPEC_FINDERS += (PathSpecFinder,) -_SPEC_FINDERS += (ExplicitNamespacePackageFinder,) - - -def _is_setuptools_namespace(location): - try: - with open(os.path.join(location, "__init__.py"), "rb") as stream: - data = stream.read(4096) - except IOError: - pass - else: - extend_path = b"pkgutil" in data and b"extend_path" in data - declare_namespace = ( - b"pkg_resources" in data and b"declare_namespace(__name__)" in data - ) - return extend_path or declare_namespace - - -@lru_cache() -def _cached_set_diff(left, right): - result = set(left) - result.difference_update(right) - return result - - -def _precache_zipimporters(path=None): - pic = sys.path_importer_cache - - # When measured, despite having the same complexity (O(n)), - # converting to tuples and then caching the conversion to sets - # and the set difference is faster than converting to sets - # and then only caching the set difference. - - req_paths = tuple(path or sys.path) - cached_paths = tuple(pic) - new_paths = _cached_set_diff(req_paths, cached_paths) - for entry_path in new_paths: - try: - pic[entry_path] = zipimport.zipimporter(entry_path) - except zipimport.ZipImportError: - continue - return pic - - -def _search_zip(modpath, pic): - for filepath, importer in list(pic.items()): - if importer is not None: - found = importer.find_module(modpath[0]) - if found: - if not importer.find_module(os.path.sep.join(modpath)): - raise ImportError( - "No module named %s in %s/%s" - % (".".join(modpath[1:]), filepath, modpath) - ) - # import code; code.interact(local=locals()) - return ( - ModuleType.PY_ZIPMODULE, - os.path.abspath(filepath) + os.path.sep + os.path.sep.join(modpath), - filepath, - ) - raise ImportError("No module named %s" % ".".join(modpath)) - - -def _find_spec_with_path(search_path, modname, module_parts, processed, submodule_path): - finders = [finder(search_path) for finder in _SPEC_FINDERS] - for finder in finders: - spec = finder.find_module(modname, module_parts, processed, submodule_path) - if spec is None: - continue - return finder, spec - - raise ImportError("No module named %s" % ".".join(module_parts)) - - -def find_spec(modpath, path=None): - """Find a spec for the given module. - - :type modpath: list or tuple - :param modpath: - split module's name (i.e name of a module or package split - on '.'), with leading empty strings for explicit relative import - - :type path: list or None - :param path: - optional list of path where the module or package should be - searched (use sys.path if nothing or None is given) - - :rtype: ModuleSpec - :return: A module spec, which describes how the module was - found and where. - """ - _path = path or sys.path - - # Need a copy for not mutating the argument. - modpath = modpath[:] - - submodule_path = None - module_parts = modpath[:] - processed = [] - - while modpath: - modname = modpath.pop(0) - finder, spec = _find_spec_with_path( - _path, modname, module_parts, processed, submodule_path or path - ) - processed.append(modname) - if modpath: - submodule_path = finder.contribute_to_path(spec, processed) - - if spec.type == ModuleType.PKG_DIRECTORY: - spec = spec._replace(submodule_search_locations=submodule_path) - - return spec diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/interpreter/_import/util.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/interpreter/_import/util.py deleted file mode 100644 index a917bd3..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/interpreter/_import/util.py +++ /dev/null @@ -1,10 +0,0 @@ -# Copyright (c) 2016, 2018 Claudiu Popa - -try: - import pkg_resources -except ImportError: - pkg_resources = None - - -def is_namespace(modname): - return pkg_resources is not None and modname in pkg_resources._namespace_packages diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/interpreter/dunder_lookup.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/interpreter/dunder_lookup.py deleted file mode 100644 index 0ae9bc9..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/interpreter/dunder_lookup.py +++ /dev/null @@ -1,66 +0,0 @@ -# Copyright (c) 2016-2018 Claudiu Popa -# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html -# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER - -"""Contains logic for retrieving special methods. - -This implementation does not rely on the dot attribute access -logic, found in ``.getattr()``. The difference between these two -is that the dunder methods are looked with the type slots -(you can find more about these here -http://lucumr.pocoo.org/2014/8/16/the-python-i-would-like-to-see/) -As such, the lookup for the special methods is actually simpler than -the dot attribute access. -""" -import itertools - -import astroid -from astroid import exceptions - - -def _lookup_in_mro(node, name): - attrs = node.locals.get(name, []) - - nodes = itertools.chain.from_iterable( - ancestor.locals.get(name, []) for ancestor in node.ancestors(recurs=True) - ) - values = list(itertools.chain(attrs, nodes)) - if not values: - raise exceptions.AttributeInferenceError(attribute=name, target=node) - - return values - - -def lookup(node, name): - """Lookup the given special method name in the given *node* - - If the special method was found, then a list of attributes - will be returned. Otherwise, `astroid.AttributeInferenceError` - is going to be raised. - """ - if isinstance( - node, (astroid.List, astroid.Tuple, astroid.Const, astroid.Dict, astroid.Set) - ): - return _builtin_lookup(node, name) - if isinstance(node, astroid.Instance): - return _lookup_in_mro(node, name) - if isinstance(node, astroid.ClassDef): - return _class_lookup(node, name) - - raise exceptions.AttributeInferenceError(attribute=name, target=node) - - -def _class_lookup(node, name): - metaclass = node.metaclass() - if metaclass is None: - raise exceptions.AttributeInferenceError(attribute=name, target=node) - - return _lookup_in_mro(metaclass, name) - - -def _builtin_lookup(node, name): - values = node.locals.get(name, []) - if not values: - raise exceptions.AttributeInferenceError(attribute=name, target=node) - - return values diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/interpreter/objectmodel.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/interpreter/objectmodel.py deleted file mode 100644 index 277c825..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/interpreter/objectmodel.py +++ /dev/null @@ -1,801 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright (c) 2016-2019 Claudiu Popa -# Copyright (c) 2016 Derek Gustafson -# Copyright (c) 2017-2018 Bryce Guinta -# Copyright (c) 2017 Ceridwen -# Copyright (c) 2017 Calen Pennington -# Copyright (c) 2018 Ville Skyttä -# Copyright (c) 2018 Nick Drozd -# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html -# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER -""" -Data object model, as per https://docs.python.org/3/reference/datamodel.html. - -This module describes, at least partially, a data object model for some -of astroid's nodes. The model contains special attributes that nodes such -as functions, classes, modules etc have, such as __doc__, __class__, -__module__ etc, being used when doing attribute lookups over nodes. - -For instance, inferring `obj.__class__` will first trigger an inference -of the `obj` variable. If it was successfully inferred, then an attribute -`__class__ will be looked for in the inferred object. This is the part -where the data model occurs. The model is attached to those nodes -and the lookup mechanism will try to see if attributes such as -`__class__` are defined by the model or not. If they are defined, -the model will be requested to return the corresponding value of that -attribute. Thus the model can be viewed as a special part of the lookup -mechanism. -""" - -import itertools -import pprint -import os -import types -from functools import lru_cache - -import astroid -from astroid import context as contextmod -from astroid import exceptions -from astroid import node_classes - - -IMPL_PREFIX = "attr_" - - -def _dunder_dict(instance, attributes): - obj = node_classes.Dict(parent=instance) - - # Convert the keys to node strings - keys = [ - node_classes.Const(value=value, parent=obj) for value in list(attributes.keys()) - ] - - # The original attribute has a list of elements for each key, - # but that is not useful for retrieving the special attribute's value. - # In this case, we're picking the last value from each list. - values = [elem[-1] for elem in attributes.values()] - - obj.postinit(list(zip(keys, values))) - return obj - - -class ObjectModel: - def __init__(self): - self._instance = None - - def __repr__(self): - result = [] - cname = type(self).__name__ - string = "%(cname)s(%(fields)s)" - alignment = len(cname) + 1 - for field in sorted(self.attributes()): - width = 80 - len(field) - alignment - lines = pprint.pformat(field, indent=2, width=width).splitlines(True) - - inner = [lines[0]] - for line in lines[1:]: - inner.append(" " * alignment + line) - result.append(field) - - return string % { - "cname": cname, - "fields": (",\n" + " " * alignment).join(result), - } - - def __call__(self, instance): - self._instance = instance - return self - - def __get__(self, instance, cls=None): - # ObjectModel needs to be a descriptor so that just doing - # `special_attributes = SomeObjectModel` should be enough in the body of a node. - # But at the same time, node.special_attributes should return an object - # which can be used for manipulating the special attributes. That's the reason - # we pass the instance through which it got accessed to ObjectModel.__call__, - # returning itself afterwards, so we can still have access to the - # underlying data model and to the instance for which it got accessed. - return self(instance) - - def __contains__(self, name): - return name in self.attributes() - - @lru_cache(maxsize=None) - def attributes(self): - """Get the attributes which are exported by this object model.""" - return [ - obj[len(IMPL_PREFIX) :] for obj in dir(self) if obj.startswith(IMPL_PREFIX) - ] - - def lookup(self, name): - """Look up the given *name* in the current model - - It should return an AST or an interpreter object, - but if the name is not found, then an AttributeInferenceError will be raised. - """ - - if name in self.attributes(): - return getattr(self, IMPL_PREFIX + name) - raise exceptions.AttributeInferenceError(target=self._instance, attribute=name) - - -class ModuleModel(ObjectModel): - def _builtins(self): - builtins_ast_module = astroid.MANAGER.builtins_module - return builtins_ast_module.special_attributes.lookup("__dict__") - - @property - def attr_builtins(self): - return self._builtins() - - @property - def attr___path__(self): - if not self._instance.package: - raise exceptions.AttributeInferenceError( - target=self._instance, attribute="__path__" - ) - - path_objs = [ - node_classes.Const( - value=path - if not path.endswith("__init__.py") - else os.path.dirname(path), - parent=self._instance, - ) - for path in self._instance.path - ] - - container = node_classes.List(parent=self._instance) - container.postinit(path_objs) - - return container - - @property - def attr___name__(self): - return node_classes.Const(value=self._instance.name, parent=self._instance) - - @property - def attr___doc__(self): - return node_classes.Const(value=self._instance.doc, parent=self._instance) - - @property - def attr___file__(self): - return node_classes.Const(value=self._instance.file, parent=self._instance) - - @property - def attr___dict__(self): - return _dunder_dict(self._instance, self._instance.globals) - - @property - def attr___package__(self): - if not self._instance.package: - value = "" - else: - value = self._instance.name - - return node_classes.Const(value=value, parent=self._instance) - - # These are related to the Python 3 implementation of the - # import system, - # https://docs.python.org/3/reference/import.html#import-related-module-attributes - - @property - def attr___spec__(self): - # No handling for now. - return node_classes.Unknown() - - @property - def attr___loader__(self): - # No handling for now. - return node_classes.Unknown() - - @property - def attr___cached__(self): - # No handling for now. - return node_classes.Unknown() - - -class FunctionModel(ObjectModel): - @property - def attr___name__(self): - return node_classes.Const(value=self._instance.name, parent=self._instance) - - @property - def attr___doc__(self): - return node_classes.Const(value=self._instance.doc, parent=self._instance) - - @property - def attr___qualname__(self): - return node_classes.Const(value=self._instance.qname(), parent=self._instance) - - @property - def attr___defaults__(self): - func = self._instance - if not func.args.defaults: - return node_classes.Const(value=None, parent=func) - - defaults_obj = node_classes.Tuple(parent=func) - defaults_obj.postinit(func.args.defaults) - return defaults_obj - - @property - def attr___annotations__(self): - obj = node_classes.Dict(parent=self._instance) - - if not self._instance.returns: - returns = None - else: - returns = self._instance.returns - - args = self._instance.args - pair_annotations = itertools.chain( - zip(args.args or [], args.annotations), - zip(args.kwonlyargs, args.kwonlyargs_annotations), - zip(args.posonlyargs or [], args.posonlyargs_annotations), - ) - - annotations = { - arg.name: annotation for (arg, annotation) in pair_annotations if annotation - } - if args.varargannotation: - annotations[args.vararg] = args.varargannotation - if args.kwargannotation: - annotations[args.kwarg] = args.kwargannotation - if returns: - annotations["return"] = returns - - items = [ - (node_classes.Const(key, parent=obj), value) - for (key, value) in annotations.items() - ] - - obj.postinit(items) - return obj - - @property - def attr___dict__(self): - return node_classes.Dict(parent=self._instance) - - attr___globals__ = attr___dict__ - - @property - def attr___kwdefaults__(self): - def _default_args(args, parent): - for arg in args.kwonlyargs: - try: - default = args.default_value(arg.name) - except exceptions.NoDefault: - continue - - name = node_classes.Const(arg.name, parent=parent) - yield name, default - - args = self._instance.args - obj = node_classes.Dict(parent=self._instance) - defaults = dict(_default_args(args, obj)) - - obj.postinit(list(defaults.items())) - return obj - - @property - def attr___module__(self): - return node_classes.Const(self._instance.root().qname()) - - @property - def attr___get__(self): - # pylint: disable=import-outside-toplevel; circular import - from astroid import bases - - func = self._instance - - class DescriptorBoundMethod(bases.BoundMethod): - """Bound method which knows how to understand calling descriptor binding.""" - - def implicit_parameters(self): - # Different than BoundMethod since the signature - # is different. - return 0 - - def infer_call_result(self, caller, context=None): - if len(caller.args) > 2 or len(caller.args) < 1: - raise exceptions.InferenceError( - "Invalid arguments for descriptor binding", - target=self, - context=context, - ) - - context = contextmod.copy_context(context) - cls = next(caller.args[0].infer(context=context)) - - if cls is astroid.Uninferable: - raise exceptions.InferenceError( - "Invalid class inferred", target=self, context=context - ) - - # For some reason func is a Node that the below - # code is not expecting - if isinstance(func, bases.BoundMethod): - yield func - return - - # Rebuild the original value, but with the parent set as the - # class where it will be bound. - new_func = func.__class__( - name=func.name, - doc=func.doc, - lineno=func.lineno, - col_offset=func.col_offset, - ) - # pylint: disable=no-member - new_func.postinit(func.args, func.body, func.decorators, func.returns) - - # Build a proper bound method that points to our newly built function. - proxy = bases.UnboundMethod(new_func) - yield bases.BoundMethod(proxy=proxy, bound=cls) - - @property - def args(self): - """Overwrite the underlying args to match those of the underlying func - - Usually the underlying *func* is a function/method, as in: - - def test(self): - pass - - This has only the *self* parameter but when we access test.__get__ - we get a new object which has two parameters, *self* and *type*. - """ - nonlocal func - positional_or_keyword_params = func.args.args.copy() - positional_or_keyword_params.append(astroid.AssignName(name="type")) - - positional_only_params = func.args.posonlyargs.copy() - - arguments = astroid.Arguments(parent=func.args.parent) - arguments.postinit( - args=positional_or_keyword_params, - posonlyargs=positional_only_params, - defaults=[], - kwonlyargs=[], - kw_defaults=[], - annotations=[], - ) - return arguments - - return DescriptorBoundMethod(proxy=self._instance, bound=self._instance) - - # These are here just for completion. - @property - def attr___ne__(self): - return node_classes.Unknown() - - attr___subclasshook__ = attr___ne__ - attr___str__ = attr___ne__ - attr___sizeof__ = attr___ne__ - attr___setattr___ = attr___ne__ - attr___repr__ = attr___ne__ - attr___reduce__ = attr___ne__ - attr___reduce_ex__ = attr___ne__ - attr___new__ = attr___ne__ - attr___lt__ = attr___ne__ - attr___eq__ = attr___ne__ - attr___gt__ = attr___ne__ - attr___format__ = attr___ne__ - attr___delattr___ = attr___ne__ - attr___getattribute__ = attr___ne__ - attr___hash__ = attr___ne__ - attr___init__ = attr___ne__ - attr___dir__ = attr___ne__ - attr___call__ = attr___ne__ - attr___class__ = attr___ne__ - attr___closure__ = attr___ne__ - attr___code__ = attr___ne__ - - -class ClassModel(ObjectModel): - @property - def attr___module__(self): - return node_classes.Const(self._instance.root().qname()) - - @property - def attr___name__(self): - return node_classes.Const(self._instance.name) - - @property - def attr___qualname__(self): - return node_classes.Const(self._instance.qname()) - - @property - def attr___doc__(self): - return node_classes.Const(self._instance.doc) - - @property - def attr___mro__(self): - if not self._instance.newstyle: - raise exceptions.AttributeInferenceError( - target=self._instance, attribute="__mro__" - ) - - mro = self._instance.mro() - obj = node_classes.Tuple(parent=self._instance) - obj.postinit(mro) - return obj - - @property - def attr_mro(self): - if not self._instance.newstyle: - raise exceptions.AttributeInferenceError( - target=self._instance, attribute="mro" - ) - - # pylint: disable=import-outside-toplevel; circular import - from astroid import bases - - other_self = self - - # Cls.mro is a method and we need to return one in order to have a proper inference. - # The method we're returning is capable of inferring the underlying MRO though. - class MroBoundMethod(bases.BoundMethod): - def infer_call_result(self, caller, context=None): - yield other_self.attr___mro__ - - implicit_metaclass = self._instance.implicit_metaclass() - mro_method = implicit_metaclass.locals["mro"][0] - return MroBoundMethod(proxy=mro_method, bound=implicit_metaclass) - - @property - def attr___bases__(self): - obj = node_classes.Tuple() - context = contextmod.InferenceContext() - elts = list(self._instance._inferred_bases(context)) - obj.postinit(elts=elts) - return obj - - @property - def attr___class__(self): - # pylint: disable=import-outside-toplevel; circular import - from astroid import helpers - - return helpers.object_type(self._instance) - - @property - def attr___subclasses__(self): - """Get the subclasses of the underlying class - - This looks only in the current module for retrieving the subclasses, - thus it might miss a couple of them. - """ - # pylint: disable=import-outside-toplevel; circular import - from astroid import bases - from astroid import scoped_nodes - - if not self._instance.newstyle: - raise exceptions.AttributeInferenceError( - target=self._instance, attribute="__subclasses__" - ) - - qname = self._instance.qname() - root = self._instance.root() - classes = [ - cls - for cls in root.nodes_of_class(scoped_nodes.ClassDef) - if cls != self._instance and cls.is_subtype_of(qname) - ] - - obj = node_classes.List(parent=self._instance) - obj.postinit(classes) - - class SubclassesBoundMethod(bases.BoundMethod): - def infer_call_result(self, caller, context=None): - yield obj - - implicit_metaclass = self._instance.implicit_metaclass() - subclasses_method = implicit_metaclass.locals["__subclasses__"][0] - return SubclassesBoundMethod(proxy=subclasses_method, bound=implicit_metaclass) - - @property - def attr___dict__(self): - return node_classes.Dict(parent=self._instance) - - -class SuperModel(ObjectModel): - @property - def attr___thisclass__(self): - return self._instance.mro_pointer - - @property - def attr___self_class__(self): - return self._instance._self_class - - @property - def attr___self__(self): - return self._instance.type - - @property - def attr___class__(self): - return self._instance._proxied - - -class UnboundMethodModel(ObjectModel): - @property - def attr___class__(self): - # pylint: disable=import-outside-toplevel; circular import - from astroid import helpers - - return helpers.object_type(self._instance) - - @property - def attr___func__(self): - return self._instance._proxied - - @property - def attr___self__(self): - return node_classes.Const(value=None, parent=self._instance) - - attr_im_func = attr___func__ - attr_im_class = attr___class__ - attr_im_self = attr___self__ - - -class BoundMethodModel(FunctionModel): - @property - def attr___func__(self): - return self._instance._proxied._proxied - - @property - def attr___self__(self): - return self._instance.bound - - -class GeneratorModel(FunctionModel): - def __new__(cls, *args, **kwargs): - # Append the values from the GeneratorType unto this object. - ret = super(GeneratorModel, cls).__new__(cls, *args, **kwargs) - generator = astroid.MANAGER.builtins_module["generator"] - for name, values in generator.locals.items(): - method = values[0] - patched = lambda cls, meth=method: meth - - setattr(type(ret), IMPL_PREFIX + name, property(patched)) - - return ret - - @property - def attr___name__(self): - return node_classes.Const( - value=self._instance.parent.name, parent=self._instance - ) - - @property - def attr___doc__(self): - return node_classes.Const( - value=self._instance.parent.doc, parent=self._instance - ) - - -class AsyncGeneratorModel(GeneratorModel): - def __new__(cls, *args, **kwargs): - # Append the values from the AGeneratorType unto this object. - ret = super().__new__(cls, *args, **kwargs) - astroid_builtins = astroid.MANAGER.builtins_module - generator = astroid_builtins.get("async_generator") - if generator is None: - # Make it backward compatible. - generator = astroid_builtins.get("generator") - - for name, values in generator.locals.items(): - method = values[0] - patched = lambda cls, meth=method: meth - - setattr(type(ret), IMPL_PREFIX + name, property(patched)) - - return ret - - -class InstanceModel(ObjectModel): - @property - def attr___class__(self): - return self._instance._proxied - - @property - def attr___module__(self): - return node_classes.Const(self._instance.root().qname()) - - @property - def attr___doc__(self): - return node_classes.Const(self._instance.doc) - - @property - def attr___dict__(self): - return _dunder_dict(self._instance, self._instance.instance_attrs) - - -# Exception instances - - -class ExceptionInstanceModel(InstanceModel): - @property - def attr_args(self): - message = node_classes.Const("") - args = node_classes.Tuple(parent=self._instance) - args.postinit((message,)) - return args - - @property - def attr___traceback__(self): - builtins_ast_module = astroid.MANAGER.builtins_module - traceback_type = builtins_ast_module[types.TracebackType.__name__] - return traceback_type.instantiate_class() - - -class SyntaxErrorInstanceModel(ExceptionInstanceModel): - @property - def attr_text(self): - return node_classes.Const("") - - -class OSErrorInstanceModel(ExceptionInstanceModel): - @property - def attr_filename(self): - return node_classes.Const("") - - @property - def attr_errno(self): - return node_classes.Const(0) - - @property - def attr_strerror(self): - return node_classes.Const("") - - attr_filename2 = attr_filename - - -class ImportErrorInstanceModel(ExceptionInstanceModel): - @property - def attr_name(self): - return node_classes.Const("") - - @property - def attr_path(self): - return node_classes.Const("") - - -BUILTIN_EXCEPTIONS = { - "builtins.SyntaxError": SyntaxErrorInstanceModel, - "builtins.ImportError": ImportErrorInstanceModel, - # These are all similar to OSError in terms of attributes - "builtins.OSError": OSErrorInstanceModel, - "builtins.BlockingIOError": OSErrorInstanceModel, - "builtins.BrokenPipeError": OSErrorInstanceModel, - "builtins.ChildProcessError": OSErrorInstanceModel, - "builtins.ConnectionAbortedError": OSErrorInstanceModel, - "builtins.ConnectionError": OSErrorInstanceModel, - "builtins.ConnectionRefusedError": OSErrorInstanceModel, - "builtins.ConnectionResetError": OSErrorInstanceModel, - "builtins.FileExistsError": OSErrorInstanceModel, - "builtins.FileNotFoundError": OSErrorInstanceModel, - "builtins.InterruptedError": OSErrorInstanceModel, - "builtins.IsADirectoryError": OSErrorInstanceModel, - "builtins.NotADirectoryError": OSErrorInstanceModel, - "builtins.PermissionError": OSErrorInstanceModel, - "builtins.ProcessLookupError": OSErrorInstanceModel, - "builtins.TimeoutError": OSErrorInstanceModel, -} - - -class DictModel(ObjectModel): - @property - def attr___class__(self): - return self._instance._proxied - - def _generic_dict_attribute(self, obj, name): - """Generate a bound method that can infer the given *obj*.""" - - class DictMethodBoundMethod(astroid.BoundMethod): - def infer_call_result(self, caller, context=None): - yield obj - - meth = next(self._instance._proxied.igetattr(name)) - return DictMethodBoundMethod(proxy=meth, bound=self._instance) - - @property - def attr_items(self): - elems = [] - obj = node_classes.List(parent=self._instance) - for key, value in self._instance.items: - elem = node_classes.Tuple(parent=obj) - elem.postinit((key, value)) - elems.append(elem) - obj.postinit(elts=elems) - - # pylint: disable=import-outside-toplevel; circular import - from astroid import objects - - obj = objects.DictItems(obj) - return self._generic_dict_attribute(obj, "items") - - @property - def attr_keys(self): - keys = [key for (key, _) in self._instance.items] - obj = node_classes.List(parent=self._instance) - obj.postinit(elts=keys) - - # pylint: disable=import-outside-toplevel; circular import - from astroid import objects - - obj = objects.DictKeys(obj) - return self._generic_dict_attribute(obj, "keys") - - @property - def attr_values(self): - - values = [value for (_, value) in self._instance.items] - obj = node_classes.List(parent=self._instance) - obj.postinit(values) - - # pylint: disable=import-outside-toplevel; circular import - from astroid import objects - - obj = objects.DictValues(obj) - return self._generic_dict_attribute(obj, "values") - - -class PropertyModel(ObjectModel): - """Model for a builtin property""" - - # pylint: disable=import-outside-toplevel - def _init_function(self, name): - from astroid.node_classes import Arguments - from astroid.scoped_nodes import FunctionDef - - args = Arguments() - args.postinit( - args=[], - defaults=[], - kwonlyargs=[], - kw_defaults=[], - annotations=[], - posonlyargs=[], - posonlyargs_annotations=[], - kwonlyargs_annotations=[], - ) - - function = FunctionDef(name=name, parent=self._instance) - - function.postinit(args=args, body=[]) - return function - - @property - def attr_fget(self): - from astroid.scoped_nodes import FunctionDef - - func = self._instance - - class PropertyFuncAccessor(FunctionDef): - def infer_call_result(self, caller=None, context=None): - nonlocal func - if caller and len(caller.args) != 1: - raise exceptions.InferenceError( - "fget() needs a single argument", target=self, context=context - ) - - yield from func.function.infer_call_result( - caller=caller, context=context - ) - - property_accessor = PropertyFuncAccessor(name="fget", parent=self._instance) - property_accessor.postinit(args=func.args, body=func.body) - return property_accessor - - @property - def attr_setter(self): - return self._init_function("setter") - - @property - def attr_deleter(self): - return self._init_function("deleter") - - @property - def attr_getter(self): - return self._init_function("getter") - - # pylint: enable=import-outside-toplevel diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/manager.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/manager.py deleted file mode 100644 index 82208ad..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/manager.py +++ /dev/null @@ -1,350 +0,0 @@ -# Copyright (c) 2006-2011, 2013-2014 LOGILAB S.A. (Paris, FRANCE) -# Copyright (c) 2014-2019 Claudiu Popa -# Copyright (c) 2014 BioGeek -# Copyright (c) 2014 Google, Inc. -# Copyright (c) 2014 Eevee (Alex Munroe) -# Copyright (c) 2015-2016 Ceridwen -# Copyright (c) 2016 Derek Gustafson -# Copyright (c) 2017 Iva Miholic -# Copyright (c) 2018 Bryce Guinta -# Copyright (c) 2018 Nick Drozd -# Copyright (c) 2019 Raphael Gaschignard -# Copyright (c) 2020 Anubhav <35621759+anubh-v@users.noreply.github.com> -# Copyright (c) 2020 Ashley Whetter - -# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html -# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER - -"""astroid manager: avoid multiple astroid build of a same module when -possible by providing a class responsible to get astroid representation -from various source and using a cache of built modules) -""" - -import os -import zipimport - -from astroid import exceptions -from astroid.interpreter._import import spec -from astroid import modutils -from astroid import transforms - - -ZIP_IMPORT_EXTS = (".zip", ".egg", ".whl") - - -def safe_repr(obj): - try: - return repr(obj) - except Exception: # pylint: disable=broad-except - return "???" - - -class AstroidManager: - """the astroid manager, responsible to build astroid from files - or modules. - - Use the Borg pattern. - """ - - name = "astroid loader" - brain = {} - - def __init__(self): - self.__dict__ = AstroidManager.brain - if not self.__dict__: - # NOTE: cache entries are added by the [re]builder - self.astroid_cache = {} - self._mod_file_cache = {} - self._failed_import_hooks = [] - self.always_load_extensions = False - self.optimize_ast = False - self.extension_package_whitelist = set() - self._transform = transforms.TransformVisitor() - - # Export these APIs for convenience - self.register_transform = self._transform.register_transform - self.unregister_transform = self._transform.unregister_transform - self.max_inferable_values = 100 - - @property - def builtins_module(self): - return self.astroid_cache["builtins"] - - def visit_transforms(self, node): - """Visit the transforms and apply them to the given *node*.""" - return self._transform.visit(node) - - def ast_from_file(self, filepath, modname=None, fallback=True, source=False): - """given a module name, return the astroid object""" - try: - filepath = modutils.get_source_file(filepath, include_no_ext=True) - source = True - except modutils.NoSourceFile: - pass - if modname is None: - try: - modname = ".".join(modutils.modpath_from_file(filepath)) - except ImportError: - modname = filepath - if ( - modname in self.astroid_cache - and self.astroid_cache[modname].file == filepath - ): - return self.astroid_cache[modname] - if source: - # pylint: disable=import-outside-toplevel; circular import - from astroid.builder import AstroidBuilder - - return AstroidBuilder(self).file_build(filepath, modname) - if fallback and modname: - return self.ast_from_module_name(modname) - raise exceptions.AstroidBuildingError( - "Unable to build an AST for {path}.", path=filepath - ) - - def ast_from_string(self, data, modname="", filepath=None): - """ Given some source code as a string, return its corresponding astroid object""" - # pylint: disable=import-outside-toplevel; circular import - from astroid.builder import AstroidBuilder - - return AstroidBuilder(self).string_build(data, modname, filepath) - - def _build_stub_module(self, modname): - # pylint: disable=import-outside-toplevel; circular import - from astroid.builder import AstroidBuilder - - return AstroidBuilder(self).string_build("", modname) - - def _build_namespace_module(self, modname, path): - # pylint: disable=import-outside-toplevel; circular import - from astroid.builder import build_namespace_package_module - - return build_namespace_package_module(modname, path) - - def _can_load_extension(self, modname): - if self.always_load_extensions: - return True - if modutils.is_standard_module(modname): - return True - parts = modname.split(".") - return any( - ".".join(parts[:x]) in self.extension_package_whitelist - for x in range(1, len(parts) + 1) - ) - - def ast_from_module_name(self, modname, context_file=None): - """given a module name, return the astroid object""" - if modname in self.astroid_cache: - return self.astroid_cache[modname] - if modname == "__main__": - return self._build_stub_module(modname) - if context_file: - old_cwd = os.getcwd() - os.chdir(os.path.dirname(context_file)) - try: - found_spec = self.file_from_module_name(modname, context_file) - if found_spec.type == spec.ModuleType.PY_ZIPMODULE: - module = self.zip_import_data(found_spec.location) - if module is not None: - return module - - elif found_spec.type in ( - spec.ModuleType.C_BUILTIN, - spec.ModuleType.C_EXTENSION, - ): - if ( - found_spec.type == spec.ModuleType.C_EXTENSION - and not self._can_load_extension(modname) - ): - return self._build_stub_module(modname) - try: - module = modutils.load_module_from_name(modname) - except Exception as ex: - raise exceptions.AstroidImportError( - "Loading {modname} failed with:\n{error}", - modname=modname, - path=found_spec.location, - ) from ex - return self.ast_from_module(module, modname) - - elif found_spec.type == spec.ModuleType.PY_COMPILED: - raise exceptions.AstroidImportError( - "Unable to load compiled module {modname}.", - modname=modname, - path=found_spec.location, - ) - - elif found_spec.type == spec.ModuleType.PY_NAMESPACE: - return self._build_namespace_module( - modname, found_spec.submodule_search_locations - ) - elif found_spec.type == spec.ModuleType.PY_FROZEN: - return self._build_stub_module(modname) - - if found_spec.location is None: - raise exceptions.AstroidImportError( - "Can't find a file for module {modname}.", modname=modname - ) - - return self.ast_from_file(found_spec.location, modname, fallback=False) - except exceptions.AstroidBuildingError as e: - for hook in self._failed_import_hooks: - try: - return hook(modname) - except exceptions.AstroidBuildingError: - pass - raise e - finally: - if context_file: - os.chdir(old_cwd) - - def zip_import_data(self, filepath): - if zipimport is None: - return None - - # pylint: disable=import-outside-toplevel; circular import - from astroid.builder import AstroidBuilder - - builder = AstroidBuilder(self) - for ext in ZIP_IMPORT_EXTS: - try: - eggpath, resource = filepath.rsplit(ext + os.path.sep, 1) - except ValueError: - continue - try: - importer = zipimport.zipimporter(eggpath + ext) - zmodname = resource.replace(os.path.sep, ".") - if importer.is_package(resource): - zmodname = zmodname + ".__init__" - module = builder.string_build( - importer.get_source(resource), zmodname, filepath - ) - return module - except Exception: # pylint: disable=broad-except - continue - return None - - def file_from_module_name(self, modname, contextfile): - try: - value = self._mod_file_cache[(modname, contextfile)] - except KeyError: - try: - value = modutils.file_info_from_modpath( - modname.split("."), context_file=contextfile - ) - except ImportError as ex: - value = exceptions.AstroidImportError( - "Failed to import module {modname} with error:\n{error}.", - modname=modname, - error=ex, - ) - self._mod_file_cache[(modname, contextfile)] = value - if isinstance(value, exceptions.AstroidBuildingError): - raise value - return value - - def ast_from_module(self, module, modname=None): - """given an imported module, return the astroid object""" - modname = modname or module.__name__ - if modname in self.astroid_cache: - return self.astroid_cache[modname] - try: - # some builtin modules don't have __file__ attribute - filepath = module.__file__ - if modutils.is_python_source(filepath): - return self.ast_from_file(filepath, modname) - except AttributeError: - pass - - # pylint: disable=import-outside-toplevel; circular import - from astroid.builder import AstroidBuilder - - return AstroidBuilder(self).module_build(module, modname) - - def ast_from_class(self, klass, modname=None): - """get astroid for the given class""" - if modname is None: - try: - modname = klass.__module__ - except AttributeError as exc: - raise exceptions.AstroidBuildingError( - "Unable to get module for class {class_name}.", - cls=klass, - class_repr=safe_repr(klass), - modname=modname, - ) from exc - modastroid = self.ast_from_module_name(modname) - return modastroid.getattr(klass.__name__)[0] # XXX - - def infer_ast_from_something(self, obj, context=None): - """infer astroid for the given class""" - if hasattr(obj, "__class__") and not isinstance(obj, type): - klass = obj.__class__ - else: - klass = obj - try: - modname = klass.__module__ - except AttributeError as exc: - raise exceptions.AstroidBuildingError( - "Unable to get module for {class_repr}.", - cls=klass, - class_repr=safe_repr(klass), - ) from exc - except Exception as exc: - raise exceptions.AstroidImportError( - "Unexpected error while retrieving module for {class_repr}:\n" - "{error}", - cls=klass, - class_repr=safe_repr(klass), - ) from exc - try: - name = klass.__name__ - except AttributeError as exc: - raise exceptions.AstroidBuildingError( - "Unable to get name for {class_repr}:\n", - cls=klass, - class_repr=safe_repr(klass), - ) from exc - except Exception as exc: - raise exceptions.AstroidImportError( - "Unexpected error while retrieving name for {class_repr}:\n" "{error}", - cls=klass, - class_repr=safe_repr(klass), - ) from exc - # take care, on living object __module__ is regularly wrong :( - modastroid = self.ast_from_module_name(modname) - if klass is obj: - for inferred in modastroid.igetattr(name, context): - yield inferred - else: - for inferred in modastroid.igetattr(name, context): - yield inferred.instantiate_class() - - def register_failed_import_hook(self, hook): - """Registers a hook to resolve imports that cannot be found otherwise. - - `hook` must be a function that accepts a single argument `modname` which - contains the name of the module or package that could not be imported. - If `hook` can resolve the import, must return a node of type `astroid.Module`, - otherwise, it must raise `AstroidBuildingError`. - """ - self._failed_import_hooks.append(hook) - - def cache_module(self, module): - """Cache a module if no module with the same name is known yet.""" - self.astroid_cache.setdefault(module.name, module) - - def bootstrap(self): - """Bootstrap the required AST modules needed for the manager to work - - The bootstrap usually involves building the AST for the builtins - module, which is required by the rest of astroid to work correctly. - """ - from astroid import raw_building # pylint: disable=import-outside-toplevel - - raw_building._astroid_bootstrapping() - - def clear_cache(self): - """Clear the underlying cache. Also bootstraps the builtins module.""" - self.astroid_cache.clear() - self.bootstrap() diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/mixins.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/mixins.py deleted file mode 100644 index 497a840..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/mixins.py +++ /dev/null @@ -1,160 +0,0 @@ -# Copyright (c) 2010-2011, 2013-2014 LOGILAB S.A. (Paris, FRANCE) -# Copyright (c) 2014-2016, 2018 Claudiu Popa -# Copyright (c) 2014 Google, Inc. -# Copyright (c) 2014 Eevee (Alex Munroe) -# Copyright (c) 2015-2016 Ceridwen -# Copyright (c) 2015 Florian Bruhin -# Copyright (c) 2016 Jakub Wilk -# Copyright (c) 2018 Nick Drozd - -# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html -# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER - -"""This module contains some mixins for the different nodes. -""" -import itertools - -from astroid import decorators -from astroid import exceptions - - -class BlockRangeMixIn: - """override block range """ - - @decorators.cachedproperty - def blockstart_tolineno(self): - return self.lineno - - def _elsed_block_range(self, lineno, orelse, last=None): - """handle block line numbers range for try/finally, for, if and while - statements - """ - if lineno == self.fromlineno: - return lineno, lineno - if orelse: - if lineno >= orelse[0].fromlineno: - return lineno, orelse[-1].tolineno - return lineno, orelse[0].fromlineno - 1 - return lineno, last or self.tolineno - - -class FilterStmtsMixin: - """Mixin for statement filtering and assignment type""" - - def _get_filtered_stmts(self, _, node, _stmts, mystmt): - """method used in _filter_stmts to get statements and trigger break""" - if self.statement() is mystmt: - # original node's statement is the assignment, only keep - # current node (gen exp, list comp) - return [node], True - return _stmts, False - - def assign_type(self): - return self - - -class AssignTypeMixin: - def assign_type(self): - return self - - def _get_filtered_stmts(self, lookup_node, node, _stmts, mystmt): - """method used in filter_stmts""" - if self is mystmt: - return _stmts, True - if self.statement() is mystmt: - # original node's statement is the assignment, only keep - # current node (gen exp, list comp) - return [node], True - return _stmts, False - - -class ParentAssignTypeMixin(AssignTypeMixin): - def assign_type(self): - return self.parent.assign_type() - - -class ImportFromMixin(FilterStmtsMixin): - """MixIn for From and Import Nodes""" - - def _infer_name(self, frame, name): - return name - - def do_import_module(self, modname=None): - """return the ast for a module whose name is imported by - """ - # handle special case where we are on a package node importing a module - # using the same name as the package, which may end in an infinite loop - # on relative imports - # XXX: no more needed ? - mymodule = self.root() - level = getattr(self, "level", None) # Import as no level - if modname is None: - modname = self.modname - # XXX we should investigate deeper if we really want to check - # importing itself: modname and mymodule.name be relative or absolute - if mymodule.relative_to_absolute_name(modname, level) == mymodule.name: - # FIXME: we used to raise InferenceError here, but why ? - return mymodule - - return mymodule.import_module( - modname, level=level, relative_only=level and level >= 1 - ) - - def real_name(self, asname): - """get name from 'as' name""" - for name, _asname in self.names: - if name == "*": - return asname - if not _asname: - name = name.split(".", 1)[0] - _asname = name - if asname == _asname: - return name - raise exceptions.AttributeInferenceError( - "Could not find original name for {attribute} in {target!r}", - target=self, - attribute=asname, - ) - - -class MultiLineBlockMixin: - """Mixin for nodes with multi-line blocks, e.g. For and FunctionDef. - Note that this does not apply to every node with a `body` field. - For instance, an If node has a multi-line body, but the body of an - IfExpr is not multi-line, and hence cannot contain Return nodes, - Assign nodes, etc. - """ - - @decorators.cachedproperty - def _multi_line_blocks(self): - return tuple(getattr(self, field) for field in self._multi_line_block_fields) - - def _get_return_nodes_skip_functions(self): - for block in self._multi_line_blocks: - for child_node in block: - if child_node.is_function: - continue - yield from child_node._get_return_nodes_skip_functions() - - def _get_yield_nodes_skip_lambdas(self): - for block in self._multi_line_blocks: - for child_node in block: - if child_node.is_lambda: - continue - yield from child_node._get_yield_nodes_skip_lambdas() - - @decorators.cached - def _get_assign_nodes(self): - children_assign_nodes = ( - child_node._get_assign_nodes() - for block in self._multi_line_blocks - for child_node in block - ) - return list(itertools.chain.from_iterable(children_assign_nodes)) - - -class NoChildrenMixin: - """Mixin for nodes with no children, e.g. Pass.""" - - def get_children(self): - yield from () diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/modutils.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/modutils.py deleted file mode 100644 index 4e6ed86..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/modutils.py +++ /dev/null @@ -1,690 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright (c) 2014-2018, 2020 Claudiu Popa -# Copyright (c) 2014 Google, Inc. -# Copyright (c) 2014 Denis Laxalde -# Copyright (c) 2014 LOGILAB S.A. (Paris, FRANCE) -# Copyright (c) 2014 Eevee (Alex Munroe) -# Copyright (c) 2015 Florian Bruhin -# Copyright (c) 2015 Radosław Ganczarek -# Copyright (c) 2016 Derek Gustafson -# Copyright (c) 2016 Jakub Wilk -# Copyright (c) 2016 Ceridwen -# Copyright (c) 2018 Ville Skyttä -# Copyright (c) 2018 Mario Corchero -# Copyright (c) 2018 Mario Corchero -# Copyright (c) 2018 Anthony Sottile -# Copyright (c) 2019 Hugo van Kemenade -# Copyright (c) 2019 markmcclain -# Copyright (c) 2019 BasPH - -# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html -# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER - -"""Python modules manipulation utility functions. - -:type PY_SOURCE_EXTS: tuple(str) -:var PY_SOURCE_EXTS: list of possible python source file extension - -:type STD_LIB_DIRS: set of str -:var STD_LIB_DIRS: directories where standard modules are located - -:type BUILTIN_MODULES: dict -:var BUILTIN_MODULES: dictionary with builtin module names has key -""" -import imp -import os -import platform -import sys -import itertools -from distutils.sysconfig import get_python_lib # pylint: disable=import-error - -# pylint: disable=import-error, no-name-in-module -from distutils.errors import DistutilsPlatformError - -# distutils is replaced by virtualenv with a module that does -# weird path manipulations in order to get to the -# real distutils module. -from typing import Optional, List - -from .interpreter._import import spec -from .interpreter._import import util - -if sys.platform.startswith("win"): - PY_SOURCE_EXTS = ("py", "pyw") - PY_COMPILED_EXTS = ("dll", "pyd") -else: - PY_SOURCE_EXTS = ("py",) - PY_COMPILED_EXTS = ("so",) - - -try: - # The explicit sys.prefix is to work around a patch in virtualenv that - # replaces the 'real' sys.prefix (i.e. the location of the binary) - # with the prefix from which the virtualenv was created. This throws - # off the detection logic for standard library modules, thus the - # workaround. - STD_LIB_DIRS = { - get_python_lib(standard_lib=True, prefix=sys.prefix), - # Take care of installations where exec_prefix != prefix. - get_python_lib(standard_lib=True, prefix=sys.exec_prefix), - get_python_lib(standard_lib=True), - } -# get_python_lib(standard_lib=1) is not available on pypy, set STD_LIB_DIR to -# non-valid path, see https://bugs.pypy.org/issue1164 -except DistutilsPlatformError: - STD_LIB_DIRS = set() - -if os.name == "nt": - STD_LIB_DIRS.add(os.path.join(sys.prefix, "dlls")) - try: - # real_prefix is defined when running inside virtual environments, - # created with the **virtualenv** library. - STD_LIB_DIRS.add(os.path.join(sys.real_prefix, "dlls")) - except AttributeError: - # sys.base_exec_prefix is always defined, but in a virtual environment - # created with the stdlib **venv** module, it points to the original - # installation, if the virtual env is activated. - try: - STD_LIB_DIRS.add(os.path.join(sys.base_exec_prefix, "dlls")) - except AttributeError: - pass - -if platform.python_implementation() == "PyPy": - _root = os.path.join(sys.prefix, "lib_pypy") - STD_LIB_DIRS.add(_root) - try: - # real_prefix is defined when running inside virtualenv. - STD_LIB_DIRS.add(os.path.join(sys.real_prefix, "lib_pypy")) - except AttributeError: - pass - del _root -if os.name == "posix": - # Need the real prefix is we're under a virtualenv, otherwise - # the usual one will do. - try: - prefix = sys.real_prefix - except AttributeError: - prefix = sys.prefix - - def _posix_path(path): - base_python = "python%d.%d" % sys.version_info[:2] - return os.path.join(prefix, path, base_python) - - STD_LIB_DIRS.add(_posix_path("lib")) - if sys.maxsize > 2 ** 32: - # This tries to fix a problem with /usr/lib64 builds, - # where systems are running both 32-bit and 64-bit code - # on the same machine, which reflects into the places where - # standard library could be found. More details can be found - # here http://bugs.python.org/issue1294959. - # An easy reproducing case would be - # https://github.com/PyCQA/pylint/issues/712#issuecomment-163178753 - STD_LIB_DIRS.add(_posix_path("lib64")) - -EXT_LIB_DIRS = {get_python_lib(), get_python_lib(True)} -IS_JYTHON = platform.python_implementation() == "Jython" -BUILTIN_MODULES = dict.fromkeys(sys.builtin_module_names, True) - - -class NoSourceFile(Exception): - """exception raised when we are not able to get a python - source file for a precompiled file - """ - - -def _normalize_path(path): - return os.path.normcase(os.path.abspath(path)) - - -def _canonicalize_path(path): - return os.path.realpath(os.path.expanduser(path)) - - -def _path_from_filename(filename, is_jython=IS_JYTHON): - if not is_jython: - return filename - head, has_pyclass, _ = filename.partition("$py.class") - if has_pyclass: - return head + ".py" - return filename - - -def _handle_blacklist(blacklist, dirnames, filenames): - """remove files/directories in the black list - - dirnames/filenames are usually from os.walk - """ - for norecurs in blacklist: - if norecurs in dirnames: - dirnames.remove(norecurs) - elif norecurs in filenames: - filenames.remove(norecurs) - - -_NORM_PATH_CACHE = {} - - -def _cache_normalize_path(path): - """abspath with caching""" - # _module_file calls abspath on every path in sys.path every time it's - # called; on a larger codebase this easily adds up to half a second just - # assembling path components. This cache alleviates that. - try: - return _NORM_PATH_CACHE[path] - except KeyError: - if not path: # don't cache result for '' - return _normalize_path(path) - result = _NORM_PATH_CACHE[path] = _normalize_path(path) - return result - - -def load_module_from_name(dotted_name, path=None, use_sys=True): - """Load a Python module from its name. - - :type dotted_name: str - :param dotted_name: python name of a module or package - - :type path: list or None - :param path: - optional list of path where the module or package should be - searched (use sys.path if nothing or None is given) - - :type use_sys: bool - :param use_sys: - boolean indicating whether the sys.modules dictionary should be - used or not - - - :raise ImportError: if the module or package is not found - - :rtype: module - :return: the loaded module - """ - return load_module_from_modpath(dotted_name.split("."), path, use_sys) - - -def load_module_from_modpath(parts, path: Optional[List[str]] = None, use_sys=1): - """Load a python module from its split name. - - :type parts: list(str) or tuple(str) - :param parts: - python name of a module or package split on '.' - - :param path: - Optional list of path where the module or package should be - searched (use sys.path if nothing or None is given) - - :type use_sys: bool - :param use_sys: - boolean indicating whether the sys.modules dictionary should be used or not - - :raise ImportError: if the module or package is not found - - :rtype: module - :return: the loaded module - """ - if use_sys: - try: - return sys.modules[".".join(parts)] - except KeyError: - pass - modpath = [] - prevmodule = None - for part in parts: - modpath.append(part) - curname = ".".join(modpath) - module = None - if len(modpath) != len(parts): - # even with use_sys=False, should try to get outer packages from sys.modules - module = sys.modules.get(curname) - elif use_sys: - # because it may have been indirectly loaded through a parent - module = sys.modules.get(curname) - if module is None: - mp_file, mp_filename, mp_desc = imp.find_module(part, path) - module = imp.load_module(curname, mp_file, mp_filename, mp_desc) - # mp_file still needs to be closed. - if mp_file: - mp_file.close() - if prevmodule: - setattr(prevmodule, part, module) - _file = getattr(module, "__file__", "") - prevmodule = module - if not _file and util.is_namespace(curname): - continue - if not _file and len(modpath) != len(parts): - raise ImportError("no module in %s" % ".".join(parts[len(modpath) :])) - path = [os.path.dirname(_file)] - return module - - -def load_module_from_file( - filepath: str, path: Optional[List[str]] = None, use_sys=True -): - """Load a Python module from it's path. - - :type filepath: str - :param filepath: path to the python module or package - - :param Optional[List[str]] path: - Optional list of path where the module or package should be - searched (use sys.path if nothing or None is given) - - :type use_sys: bool - :param use_sys: - boolean indicating whether the sys.modules dictionary should be - used or not - - :raise ImportError: if the module or package is not found - - :rtype: module - :return: the loaded module - """ - modpath = modpath_from_file(filepath) - return load_module_from_modpath(modpath, path, use_sys) - - -def check_modpath_has_init(path, mod_path): - """check there are some __init__.py all along the way""" - modpath = [] - for part in mod_path: - modpath.append(part) - path = os.path.join(path, part) - if not _has_init(path): - old_namespace = util.is_namespace(".".join(modpath)) - if not old_namespace: - return False - return True - - -def _get_relative_base_path(filename, path_to_check): - """Extracts the relative mod path of the file to import from - - Check if a file is within the passed in path and if so, returns the - relative mod path from the one passed in. - - If the filename is no in path_to_check, returns None - - Note this function will look for both abs and realpath of the file, - this allows to find the relative base path even if the file is a - symlink of a file in the passed in path - - Examples: - _get_relative_base_path("/a/b/c/d.py", "/a/b") -> ["c","d"] - _get_relative_base_path("/a/b/c/d.py", "/dev") -> None - """ - importable_path = None - path_to_check = os.path.normcase(path_to_check) - abs_filename = os.path.abspath(filename) - if os.path.normcase(abs_filename).startswith(path_to_check): - importable_path = abs_filename - - real_filename = os.path.realpath(filename) - if os.path.normcase(real_filename).startswith(path_to_check): - importable_path = real_filename - - if importable_path: - base_path = os.path.splitext(importable_path)[0] - relative_base_path = base_path[len(path_to_check) :] - return [pkg for pkg in relative_base_path.split(os.sep) if pkg] - - return None - - -def modpath_from_file_with_callback(filename, path=None, is_package_cb=None): - filename = os.path.expanduser(_path_from_filename(filename)) - for pathname in itertools.chain( - path or [], map(_canonicalize_path, sys.path), sys.path - ): - pathname = _cache_normalize_path(pathname) - if not pathname: - continue - modpath = _get_relative_base_path(filename, pathname) - if not modpath: - continue - if is_package_cb(pathname, modpath[:-1]): - return modpath - - raise ImportError( - "Unable to find module for %s in %s" % (filename, ", \n".join(sys.path)) - ) - - -def modpath_from_file(filename, path=None): - """Get the corresponding split module's name from a filename - - This function will return the name of a module or package split on `.`. - - :type filename: str - :param filename: file's path for which we want the module's name - - :type Optional[List[str]] path: - Optional list of path where the module or package should be - searched (use sys.path if nothing or None is given) - - :raise ImportError: - if the corresponding module's name has not been found - - :rtype: list(str) - :return: the corresponding split module's name - """ - return modpath_from_file_with_callback(filename, path, check_modpath_has_init) - - -def file_from_modpath(modpath, path=None, context_file=None): - return file_info_from_modpath(modpath, path, context_file).location - - -def file_info_from_modpath(modpath, path=None, context_file=None): - """given a mod path (i.e. split module / package name), return the - corresponding file, giving priority to source file over precompiled - file if it exists - - :type modpath: list or tuple - :param modpath: - split module's name (i.e name of a module or package split - on '.') - (this means explicit relative imports that start with dots have - empty strings in this list!) - - :type path: list or None - :param path: - optional list of path where the module or package should be - searched (use sys.path if nothing or None is given) - - :type context_file: str or None - :param context_file: - context file to consider, necessary if the identifier has been - introduced using a relative import unresolvable in the actual - context (i.e. modutils) - - :raise ImportError: if there is no such module in the directory - - :rtype: (str or None, import type) - :return: - the path to the module's file or None if it's an integrated - builtin module such as 'sys' - """ - if context_file is not None: - context = os.path.dirname(context_file) - else: - context = context_file - if modpath[0] == "xml": - # handle _xmlplus - try: - return _spec_from_modpath(["_xmlplus"] + modpath[1:], path, context) - except ImportError: - return _spec_from_modpath(modpath, path, context) - elif modpath == ["os", "path"]: - # FIXME: currently ignoring search_path... - return spec.ModuleSpec( - name="os.path", location=os.path.__file__, module_type=imp.PY_SOURCE - ) - return _spec_from_modpath(modpath, path, context) - - -def get_module_part(dotted_name, context_file=None): - """given a dotted name return the module part of the name : - - >>> get_module_part('astroid.as_string.dump') - 'astroid.as_string' - - :type dotted_name: str - :param dotted_name: full name of the identifier we are interested in - - :type context_file: str or None - :param context_file: - context file to consider, necessary if the identifier has been - introduced using a relative import unresolvable in the actual - context (i.e. modutils) - - - :raise ImportError: if there is no such module in the directory - - :rtype: str or None - :return: - the module part of the name or None if we have not been able at - all to import the given name - - XXX: deprecated, since it doesn't handle package precedence over module - (see #10066) - """ - # os.path trick - if dotted_name.startswith("os.path"): - return "os.path" - parts = dotted_name.split(".") - if context_file is not None: - # first check for builtin module which won't be considered latter - # in that case (path != None) - if parts[0] in BUILTIN_MODULES: - if len(parts) > 2: - raise ImportError(dotted_name) - return parts[0] - # don't use += or insert, we want a new list to be created ! - path = None - starti = 0 - if parts[0] == "": - assert ( - context_file is not None - ), "explicit relative import, but no context_file?" - path = [] # prevent resolving the import non-relatively - starti = 1 - while parts[starti] == "": # for all further dots: change context - starti += 1 - context_file = os.path.dirname(context_file) - for i in range(starti, len(parts)): - try: - file_from_modpath( - parts[starti : i + 1], path=path, context_file=context_file - ) - except ImportError: - if i < max(1, len(parts) - 2): - raise - return ".".join(parts[:i]) - return dotted_name - - -def get_module_files(src_directory, blacklist, list_all=False): - """given a package directory return a list of all available python - module's files in the package and its subpackages - - :type src_directory: str - :param src_directory: - path of the directory corresponding to the package - - :type blacklist: list or tuple - :param blacklist: iterable - list of files or directories to ignore. - - :type list_all: bool - :param list_all: - get files from all paths, including ones without __init__.py - - :rtype: list - :return: - the list of all available python module's files in the package and - its subpackages - """ - files = [] - for directory, dirnames, filenames in os.walk(src_directory): - if directory in blacklist: - continue - _handle_blacklist(blacklist, dirnames, filenames) - # check for __init__.py - if not list_all and "__init__.py" not in filenames: - dirnames[:] = () - continue - for filename in filenames: - if _is_python_file(filename): - src = os.path.join(directory, filename) - files.append(src) - return files - - -def get_source_file(filename, include_no_ext=False): - """given a python module's file name return the matching source file - name (the filename will be returned identically if it's already an - absolute path to a python source file...) - - :type filename: str - :param filename: python module's file name - - - :raise NoSourceFile: if no source file exists on the file system - - :rtype: str - :return: the absolute path of the source file if it exists - """ - filename = os.path.abspath(_path_from_filename(filename)) - base, orig_ext = os.path.splitext(filename) - for ext in PY_SOURCE_EXTS: - source_path = "%s.%s" % (base, ext) - if os.path.exists(source_path): - return source_path - if include_no_ext and not orig_ext and os.path.exists(base): - return base - raise NoSourceFile(filename) - - -def is_python_source(filename): - """ - rtype: bool - return: True if the filename is a python source file - """ - return os.path.splitext(filename)[1][1:] in PY_SOURCE_EXTS - - -def is_standard_module(modname, std_path=None): - """try to guess if a module is a standard python module (by default, - see `std_path` parameter's description) - - :type modname: str - :param modname: name of the module we are interested in - - :type std_path: list(str) or tuple(str) - :param std_path: list of path considered has standard - - - :rtype: bool - :return: - true if the module: - - is located on the path listed in one of the directory in `std_path` - - is a built-in module - """ - modname = modname.split(".")[0] - try: - filename = file_from_modpath([modname]) - except ImportError: - # import failed, i'm probably not so wrong by supposing it's - # not standard... - return False - # modules which are not living in a file are considered standard - # (sys and __builtin__ for instance) - if filename is None: - # we assume there are no namespaces in stdlib - return not util.is_namespace(modname) - filename = _normalize_path(filename) - for path in EXT_LIB_DIRS: - if filename.startswith(_cache_normalize_path(path)): - return False - if std_path is None: - std_path = STD_LIB_DIRS - for path in std_path: - if filename.startswith(_cache_normalize_path(path)): - return True - return False - - -def is_relative(modname, from_file): - """return true if the given module name is relative to the given - file name - - :type modname: str - :param modname: name of the module we are interested in - - :type from_file: str - :param from_file: - path of the module from which modname has been imported - - :rtype: bool - :return: - true if the module has been imported relatively to `from_file` - """ - if not os.path.isdir(from_file): - from_file = os.path.dirname(from_file) - if from_file in sys.path: - return False - try: - stream, _, _ = imp.find_module(modname.split(".")[0], [from_file]) - - # Close the stream to avoid ResourceWarnings. - if stream: - stream.close() - return True - except ImportError: - return False - - -# internal only functions ##################################################### - - -def _spec_from_modpath(modpath, path=None, context=None): - """given a mod path (i.e. split module / package name), return the - corresponding spec - - this function is used internally, see `file_from_modpath`'s - documentation for more information - """ - assert modpath - location = None - if context is not None: - try: - found_spec = spec.find_spec(modpath, [context]) - location = found_spec.location - except ImportError: - found_spec = spec.find_spec(modpath, path) - location = found_spec.location - else: - found_spec = spec.find_spec(modpath, path) - if found_spec.type == spec.ModuleType.PY_COMPILED: - try: - location = get_source_file(found_spec.location) - return found_spec._replace( - location=location, type=spec.ModuleType.PY_SOURCE - ) - except NoSourceFile: - return found_spec._replace(location=location) - elif found_spec.type == spec.ModuleType.C_BUILTIN: - # integrated builtin module - return found_spec._replace(location=None) - elif found_spec.type == spec.ModuleType.PKG_DIRECTORY: - location = _has_init(found_spec.location) - return found_spec._replace(location=location, type=spec.ModuleType.PY_SOURCE) - return found_spec - - -def _is_python_file(filename): - """return true if the given filename should be considered as a python file - - .pyc and .pyo are ignored - """ - return filename.endswith((".py", ".so", ".pyd", ".pyw")) - - -def _has_init(directory): - """if the given directory has a valid __init__ file, return its path, - else return None - """ - mod_or_pack = os.path.join(directory, "__init__") - for ext in PY_SOURCE_EXTS + ("pyc", "pyo"): - if os.path.exists(mod_or_pack + "." + ext): - return mod_or_pack + "." + ext - return None - - -def is_namespace(specobj): - return specobj.type == spec.ModuleType.PY_NAMESPACE - - -def is_directory(specobj): - return specobj.type == spec.ModuleType.PKG_DIRECTORY diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/node_classes.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/node_classes.py deleted file mode 100644 index 621dc5f..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/node_classes.py +++ /dev/null @@ -1,4862 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright (c) 2009-2011, 2013-2014 LOGILAB S.A. (Paris, FRANCE) -# Copyright (c) 2010 Daniel Harding -# Copyright (c) 2012 FELD Boris -# Copyright (c) 2013-2014 Google, Inc. -# Copyright (c) 2014-2020 Claudiu Popa -# Copyright (c) 2014 Eevee (Alex Munroe) -# Copyright (c) 2015-2016 Ceridwen -# Copyright (c) 2015 Florian Bruhin -# Copyright (c) 2016-2017 Derek Gustafson -# Copyright (c) 2016 Jared Garst -# Copyright (c) 2016 Jakub Wilk -# Copyright (c) 2016 Dave Baum -# Copyright (c) 2017-2020 Ashley Whetter -# Copyright (c) 2017, 2019 Łukasz Rogalski -# Copyright (c) 2017 rr- -# Copyright (c) 2018-2019 hippo91 -# Copyright (c) 2018 Nick Drozd -# Copyright (c) 2018 Ville Skyttä -# Copyright (c) 2018 Bryce Guinta -# Copyright (c) 2018 brendanator -# Copyright (c) 2018 HoverHell -# Copyright (c) 2019 kavins14 -# Copyright (c) 2019 kavins14 - -# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html -# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER - -# pylint: disable=too-many-lines; https://github.com/PyCQA/astroid/issues/465 - -"""Module for some node classes. More nodes in scoped_nodes.py -""" - -import abc -import builtins as builtins_mod -import itertools -import pprint -import sys -from functools import lru_cache, singledispatch as _singledispatch - -from astroid import as_string -from astroid import bases -from astroid import context as contextmod -from astroid import decorators -from astroid import exceptions -from astroid import manager -from astroid import mixins -from astroid import util - - -BUILTINS = builtins_mod.__name__ -MANAGER = manager.AstroidManager() -PY38 = sys.version_info[:2] >= (3, 8) - - -def _is_const(value): - return isinstance(value, tuple(CONST_CLS)) - - -@decorators.raise_if_nothing_inferred -def unpack_infer(stmt, context=None): - """recursively generate nodes inferred by the given statement. - If the inferred value is a list or a tuple, recurse on the elements - """ - if isinstance(stmt, (List, Tuple)): - for elt in stmt.elts: - if elt is util.Uninferable: - yield elt - continue - yield from unpack_infer(elt, context) - return dict(node=stmt, context=context) - # if inferred is a final node, return it and stop - inferred = next(stmt.infer(context)) - if inferred is stmt: - yield inferred - return dict(node=stmt, context=context) - # else, infer recursively, except Uninferable object that should be returned as is - for inferred in stmt.infer(context): - if inferred is util.Uninferable: - yield inferred - else: - yield from unpack_infer(inferred, context) - - return dict(node=stmt, context=context) - - -def are_exclusive( - stmt1, stmt2, exceptions=None -): # pylint: disable=redefined-outer-name - """return true if the two given statements are mutually exclusive - - `exceptions` may be a list of exception names. If specified, discard If - branches and check one of the statement is in an exception handler catching - one of the given exceptions. - - algorithm : - 1) index stmt1's parents - 2) climb among stmt2's parents until we find a common parent - 3) if the common parent is a If or TryExcept statement, look if nodes are - in exclusive branches - """ - # index stmt1's parents - stmt1_parents = {} - children = {} - node = stmt1.parent - previous = stmt1 - while node: - stmt1_parents[node] = 1 - children[node] = previous - previous = node - node = node.parent - # climb among stmt2's parents until we find a common parent - node = stmt2.parent - previous = stmt2 - while node: - if node in stmt1_parents: - # if the common parent is a If or TryExcept statement, look if - # nodes are in exclusive branches - if isinstance(node, If) and exceptions is None: - if ( - node.locate_child(previous)[1] - is not node.locate_child(children[node])[1] - ): - return True - elif isinstance(node, TryExcept): - c2attr, c2node = node.locate_child(previous) - c1attr, c1node = node.locate_child(children[node]) - if c1node is not c2node: - first_in_body_caught_by_handlers = ( - c2attr == "handlers" - and c1attr == "body" - and previous.catch(exceptions) - ) - second_in_body_caught_by_handlers = ( - c2attr == "body" - and c1attr == "handlers" - and children[node].catch(exceptions) - ) - first_in_else_other_in_handlers = ( - c2attr == "handlers" and c1attr == "orelse" - ) - second_in_else_other_in_handlers = ( - c2attr == "orelse" and c1attr == "handlers" - ) - if any( - ( - first_in_body_caught_by_handlers, - second_in_body_caught_by_handlers, - first_in_else_other_in_handlers, - second_in_else_other_in_handlers, - ) - ): - return True - elif c2attr == "handlers" and c1attr == "handlers": - return previous is not children[node] - return False - previous = node - node = node.parent - return False - - -# getitem() helpers. - -_SLICE_SENTINEL = object() - - -def _slice_value(index, context=None): - """Get the value of the given slice index.""" - - if isinstance(index, Const): - if isinstance(index.value, (int, type(None))): - return index.value - elif index is None: - return None - else: - # Try to infer what the index actually is. - # Since we can't return all the possible values, - # we'll stop at the first possible value. - try: - inferred = next(index.infer(context=context)) - except exceptions.InferenceError: - pass - else: - if isinstance(inferred, Const): - if isinstance(inferred.value, (int, type(None))): - return inferred.value - - # Use a sentinel, because None can be a valid - # value that this function can return, - # as it is the case for unspecified bounds. - return _SLICE_SENTINEL - - -def _infer_slice(node, context=None): - lower = _slice_value(node.lower, context) - upper = _slice_value(node.upper, context) - step = _slice_value(node.step, context) - if all(elem is not _SLICE_SENTINEL for elem in (lower, upper, step)): - return slice(lower, upper, step) - - raise exceptions.AstroidTypeError( - message="Could not infer slice used in subscript", - node=node, - index=node.parent, - context=context, - ) - - -def _container_getitem(instance, elts, index, context=None): - """Get a slice or an item, using the given *index*, for the given sequence.""" - try: - if isinstance(index, Slice): - index_slice = _infer_slice(index, context=context) - new_cls = instance.__class__() - new_cls.elts = elts[index_slice] - new_cls.parent = instance.parent - return new_cls - if isinstance(index, Const): - return elts[index.value] - except IndexError as exc: - raise exceptions.AstroidIndexError( - message="Index {index!s} out of range", - node=instance, - index=index, - context=context, - ) from exc - except TypeError as exc: - raise exceptions.AstroidTypeError( - message="Type error {error!r}", node=instance, index=index, context=context - ) from exc - - raise exceptions.AstroidTypeError("Could not use %s as subscript index" % index) - - -OP_PRECEDENCE = { - op: precedence - for precedence, ops in enumerate( - [ - ["Lambda"], # lambda x: x + 1 - ["IfExp"], # 1 if True else 2 - ["or"], - ["and"], - ["not"], - ["Compare"], # in, not in, is, is not, <, <=, >, >=, !=, == - ["|"], - ["^"], - ["&"], - ["<<", ">>"], - ["+", "-"], - ["*", "@", "/", "//", "%"], - ["UnaryOp"], # +, -, ~ - ["**"], - ["Await"], - ] - ) - for op in ops -} - - -class NodeNG: - """ A node of the new Abstract Syntax Tree (AST). - - This is the base class for all Astroid node classes. - """ - - is_statement = False - """Whether this node indicates a statement. - - :type: bool - """ - optional_assign = False # True for For (and for Comprehension if py <3.0) - """Whether this node optionally assigns a variable. - - This is for loop assignments because loop won't necessarily perform an - assignment if the loop has no iterations. - This is also the case from comprehensions in Python 2. - - :type: bool - """ - is_function = False # True for FunctionDef nodes - """Whether this node indicates a function. - - :type: bool - """ - is_lambda = False - # Attributes below are set by the builder module or by raw factories - lineno = None - """The line that this node appears on in the source code. - - :type: int or None - """ - col_offset = None - """The column that this node appears on in the source code. - - :type: int or None - """ - parent = None - """The parent node in the syntax tree. - - :type: NodeNG or None - """ - _astroid_fields = () - """Node attributes that contain child nodes. - - This is redefined in most concrete classes. - - :type: tuple(str) - """ - _other_fields = () - """Node attributes that do not contain child nodes. - - :type: tuple(str) - """ - _other_other_fields = () - """Attributes that contain AST-dependent fields. - - :type: tuple(str) - """ - # instance specific inference function infer(node, context) - _explicit_inference = None - - def __init__(self, lineno=None, col_offset=None, parent=None): - """ - :param lineno: The line that this node appears on in the source code. - :type lineno: int or None - - :param col_offset: The column that this node appears on in the - source code. - :type col_offset: int or None - - :param parent: The parent node in the syntax tree. - :type parent: NodeNG or None - """ - self.lineno = lineno - self.col_offset = col_offset - self.parent = parent - - def infer(self, context=None, **kwargs): - """Get a generator of the inferred values. - - This is the main entry point to the inference system. - - .. seealso:: :ref:`inference` - - If the instance has some explicit inference function set, it will be - called instead of the default interface. - - :returns: The inferred values. - :rtype: iterable - """ - if context is not None: - context = context.extra_context.get(self, context) - if self._explicit_inference is not None: - # explicit_inference is not bound, give it self explicitly - try: - # pylint: disable=not-callable - return self._explicit_inference(self, context, **kwargs) - except exceptions.UseInferenceDefault: - pass - - if not context: - return self._infer(context, **kwargs) - - key = (self, context.lookupname, context.callcontext, context.boundnode) - if key in context.inferred: - return iter(context.inferred[key]) - - gen = context.cache_generator(key, self._infer(context, **kwargs)) - return util.limit_inference(gen, MANAGER.max_inferable_values) - - def _repr_name(self): - """Get a name for nice representation. - - This is either :attr:`name`, :attr:`attrname`, or the empty string. - - :returns: The nice name. - :rtype: str - """ - names = {"name", "attrname"} - if all(name not in self._astroid_fields for name in names): - return getattr(self, "name", getattr(self, "attrname", "")) - return "" - - def __str__(self): - rname = self._repr_name() - cname = type(self).__name__ - if rname: - string = "%(cname)s.%(rname)s(%(fields)s)" - alignment = len(cname) + len(rname) + 2 - else: - string = "%(cname)s(%(fields)s)" - alignment = len(cname) + 1 - result = [] - for field in self._other_fields + self._astroid_fields: - value = getattr(self, field) - width = 80 - len(field) - alignment - lines = pprint.pformat(value, indent=2, width=width).splitlines(True) - - inner = [lines[0]] - for line in lines[1:]: - inner.append(" " * alignment + line) - result.append("%s=%s" % (field, "".join(inner))) - - return string % { - "cname": cname, - "rname": rname, - "fields": (",\n" + " " * alignment).join(result), - } - - def __repr__(self): - rname = self._repr_name() - if rname: - string = "<%(cname)s.%(rname)s l.%(lineno)s at 0x%(id)x>" - else: - string = "<%(cname)s l.%(lineno)s at 0x%(id)x>" - return string % { - "cname": type(self).__name__, - "rname": rname, - "lineno": self.fromlineno, - "id": id(self), - } - - def accept(self, visitor): - """Visit this node using the given visitor.""" - func = getattr(visitor, "visit_" + self.__class__.__name__.lower()) - return func(self) - - def get_children(self): - """Get the child nodes below this node. - - :returns: The children. - :rtype: iterable(NodeNG) - """ - for field in self._astroid_fields: - attr = getattr(self, field) - if attr is None: - continue - if isinstance(attr, (list, tuple)): - yield from attr - else: - yield attr - - def last_child(self): - """An optimized version of list(get_children())[-1] - - :returns: The last child, or None if no children exist. - :rtype: NodeNG or None - """ - for field in self._astroid_fields[::-1]: - attr = getattr(self, field) - if not attr: # None or empty listy / tuple - continue - if isinstance(attr, (list, tuple)): - return attr[-1] - - return attr - return None - - def parent_of(self, node): - """Check if this node is the parent of the given node. - - :param node: The node to check if it is the child. - :type node: NodeNG - - :returns: True if this node is the parent of the given node, - False otherwise. - :rtype: bool - """ - parent = node.parent - while parent is not None: - if self is parent: - return True - parent = parent.parent - return False - - def statement(self): - """The first parent node, including self, marked as statement node. - - :returns: The first parent statement. - :rtype: NodeNG - """ - if self.is_statement: - return self - return self.parent.statement() - - def frame(self): - """The first parent frame node. - - A frame node is a :class:`Module`, :class:`FunctionDef`, - or :class:`ClassDef`. - - :returns: The first parent frame node. - :rtype: Module or FunctionDef or ClassDef - """ - return self.parent.frame() - - def scope(self): - """The first parent node defining a new scope. - - :returns: The first parent scope node. - :rtype: Module or FunctionDef or ClassDef or Lambda or GenExpr - """ - if self.parent: - return self.parent.scope() - return None - - def root(self): - """Return the root node of the syntax tree. - - :returns: The root node. - :rtype: Module - """ - if self.parent: - return self.parent.root() - return self - - def child_sequence(self, child): - """Search for the sequence that contains this child. - - :param child: The child node to search sequences for. - :type child: NodeNG - - :returns: The sequence containing the given child node. - :rtype: iterable(NodeNG) - - :raises AstroidError: If no sequence could be found that contains - the given child. - """ - for field in self._astroid_fields: - node_or_sequence = getattr(self, field) - if node_or_sequence is child: - return [node_or_sequence] - # /!\ compiler.ast Nodes have an __iter__ walking over child nodes - if ( - isinstance(node_or_sequence, (tuple, list)) - and child in node_or_sequence - ): - return node_or_sequence - - msg = "Could not find %s in %s's children" - raise exceptions.AstroidError(msg % (repr(child), repr(self))) - - def locate_child(self, child): - """Find the field of this node that contains the given child. - - :param child: The child node to search fields for. - :type child: NodeNG - - :returns: A tuple of the name of the field that contains the child, - and the sequence or node that contains the child node. - :rtype: tuple(str, iterable(NodeNG) or NodeNG) - - :raises AstroidError: If no field could be found that contains - the given child. - """ - for field in self._astroid_fields: - node_or_sequence = getattr(self, field) - # /!\ compiler.ast Nodes have an __iter__ walking over child nodes - if child is node_or_sequence: - return field, child - if ( - isinstance(node_or_sequence, (tuple, list)) - and child in node_or_sequence - ): - return field, node_or_sequence - msg = "Could not find %s in %s's children" - raise exceptions.AstroidError(msg % (repr(child), repr(self))) - - # FIXME : should we merge child_sequence and locate_child ? locate_child - # is only used in are_exclusive, child_sequence one time in pylint. - - def next_sibling(self): - """The next sibling statement node. - - :returns: The next sibling statement node. - :rtype: NodeNG or None - """ - return self.parent.next_sibling() - - def previous_sibling(self): - """The previous sibling statement. - - :returns: The previous sibling statement node. - :rtype: NodeNG or None - """ - return self.parent.previous_sibling() - - # these are lazy because they're relatively expensive to compute for every - # single node, and they rarely get looked at - - @decorators.cachedproperty - def fromlineno(self): - """The first line that this node appears on in the source code. - - :type: int or None - """ - if self.lineno is None: - return self._fixed_source_line() - - return self.lineno - - @decorators.cachedproperty - def tolineno(self): - """The last line that this node appears on in the source code. - - :type: int or None - """ - if not self._astroid_fields: - # can't have children - lastchild = None - else: - lastchild = self.last_child() - if lastchild is None: - return self.fromlineno - - return lastchild.tolineno - - def _fixed_source_line(self): - """Attempt to find the line that this node appears on. - - We need this method since not all nodes have :attr:`lineno` set. - - :returns: The line number of this node, - or None if this could not be determined. - :rtype: int or None - """ - line = self.lineno - _node = self - try: - while line is None: - _node = next(_node.get_children()) - line = _node.lineno - except StopIteration: - _node = self.parent - while _node and line is None: - line = _node.lineno - _node = _node.parent - return line - - def block_range(self, lineno): - """Get a range from the given line number to where this node ends. - - :param lineno: The line number to start the range at. - :type lineno: int - - :returns: The range of line numbers that this node belongs to, - starting at the given line number. - :rtype: tuple(int, int or None) - """ - return lineno, self.tolineno - - def set_local(self, name, stmt): - """Define that the given name is declared in the given statement node. - - This definition is stored on the parent scope node. - - .. seealso:: :meth:`scope` - - :param name: The name that is being defined. - :type name: str - - :param stmt: The statement that defines the given name. - :type stmt: NodeNG - """ - self.parent.set_local(name, stmt) - - def nodes_of_class(self, klass, skip_klass=None): - """Get the nodes (including this one or below) of the given types. - - :param klass: The types of node to search for. - :type klass: builtins.type or tuple(builtins.type) - - :param skip_klass: The types of node to ignore. This is useful to ignore - subclasses of :attr:`klass`. - :type skip_klass: builtins.type or tuple(builtins.type) - - :returns: The node of the given types. - :rtype: iterable(NodeNG) - """ - if isinstance(self, klass): - yield self - - if skip_klass is None: - for child_node in self.get_children(): - yield from child_node.nodes_of_class(klass, skip_klass) - - return - - for child_node in self.get_children(): - if isinstance(child_node, skip_klass): - continue - yield from child_node.nodes_of_class(klass, skip_klass) - - @decorators.cached - def _get_assign_nodes(self): - return [] - - def _get_name_nodes(self): - for child_node in self.get_children(): - yield from child_node._get_name_nodes() - - def _get_return_nodes_skip_functions(self): - yield from () - - def _get_yield_nodes_skip_lambdas(self): - yield from () - - def _infer_name(self, frame, name): - # overridden for ImportFrom, Import, Global, TryExcept and Arguments - pass - - def _infer(self, context=None): - """we don't know how to resolve a statement by default""" - # this method is overridden by most concrete classes - raise exceptions.InferenceError( - "No inference function for {node!r}.", node=self, context=context - ) - - def inferred(self): - """Get a list of the inferred values. - - .. seealso:: :ref:`inference` - - :returns: The inferred values. - :rtype: list - """ - return list(self.infer()) - - def instantiate_class(self): - """Instantiate an instance of the defined class. - - .. note:: - - On anything other than a :class:`ClassDef` this will return self. - - :returns: An instance of the defined class. - :rtype: object - """ - return self - - def has_base(self, node): - """Check if this node inherits from the given type. - - :param node: The node defining the base to look for. - Usually this is a :class:`Name` node. - :type node: NodeNG - """ - return False - - def callable(self): - """Whether this node defines something that is callable. - - :returns: True if this defines something that is callable, - False otherwise. - :rtype: bool - """ - return False - - def eq(self, value): - return False - - def as_string(self): - """Get the source code that this node represents. - - :returns: The source code. - :rtype: str - """ - return as_string.to_code(self) - - def repr_tree( - self, - ids=False, - include_linenos=False, - ast_state=False, - indent=" ", - max_depth=0, - max_width=80, - ): - """Get a string representation of the AST from this node. - - :param ids: If true, includes the ids with the node type names. - :type ids: bool - - :param include_linenos: If true, includes the line numbers and - column offsets. - :type include_linenos: bool - - :param ast_state: If true, includes information derived from - the whole AST like local and global variables. - :type ast_state: bool - - :param indent: A string to use to indent the output string. - :type indent: str - - :param max_depth: If set to a positive integer, won't return - nodes deeper than max_depth in the string. - :type max_depth: int - - :param max_width: Attempt to format the output string to stay - within this number of characters, but can exceed it under some - circumstances. Only positive integer values are valid, the default is 80. - :type max_width: int - - :returns: The string representation of the AST. - :rtype: str - """ - # pylint: disable=too-many-statements - @_singledispatch - def _repr_tree(node, result, done, cur_indent="", depth=1): - """Outputs a representation of a non-tuple/list, non-node that's - contained within an AST, including strings. - """ - lines = pprint.pformat( - node, width=max(max_width - len(cur_indent), 1) - ).splitlines(True) - result.append(lines[0]) - result.extend([cur_indent + line for line in lines[1:]]) - return len(lines) != 1 - - # pylint: disable=unused-variable; doesn't understand singledispatch - @_repr_tree.register(tuple) - @_repr_tree.register(list) - def _repr_seq(node, result, done, cur_indent="", depth=1): - """Outputs a representation of a sequence that's contained within an AST.""" - cur_indent += indent - result.append("[") - if not node: - broken = False - elif len(node) == 1: - broken = _repr_tree(node[0], result, done, cur_indent, depth) - elif len(node) == 2: - broken = _repr_tree(node[0], result, done, cur_indent, depth) - if not broken: - result.append(", ") - else: - result.append(",\n") - result.append(cur_indent) - broken = _repr_tree(node[1], result, done, cur_indent, depth) or broken - else: - result.append("\n") - result.append(cur_indent) - for child in node[:-1]: - _repr_tree(child, result, done, cur_indent, depth) - result.append(",\n") - result.append(cur_indent) - _repr_tree(node[-1], result, done, cur_indent, depth) - broken = True - result.append("]") - return broken - - # pylint: disable=unused-variable; doesn't understand singledispatch - @_repr_tree.register(NodeNG) - def _repr_node(node, result, done, cur_indent="", depth=1): - """Outputs a strings representation of an astroid node.""" - if node in done: - result.append( - indent - + " max_depth: - result.append("...") - return False - depth += 1 - cur_indent += indent - if ids: - result.append("%s<0x%x>(\n" % (type(node).__name__, id(node))) - else: - result.append("%s(" % type(node).__name__) - fields = [] - if include_linenos: - fields.extend(("lineno", "col_offset")) - fields.extend(node._other_fields) - fields.extend(node._astroid_fields) - if ast_state: - fields.extend(node._other_other_fields) - if not fields: - broken = False - elif len(fields) == 1: - result.append("%s=" % fields[0]) - broken = _repr_tree( - getattr(node, fields[0]), result, done, cur_indent, depth - ) - else: - result.append("\n") - result.append(cur_indent) - for field in fields[:-1]: - result.append("%s=" % field) - _repr_tree(getattr(node, field), result, done, cur_indent, depth) - result.append(",\n") - result.append(cur_indent) - result.append("%s=" % fields[-1]) - _repr_tree(getattr(node, fields[-1]), result, done, cur_indent, depth) - broken = True - result.append(")") - return broken - - result = [] - _repr_tree(self, result, set()) - return "".join(result) - - def bool_value(self, context=None): - """Determine the boolean value of this node. - - The boolean value of a node can have three - possible values: - - * False: For instance, empty data structures, - False, empty strings, instances which return - explicitly False from the __nonzero__ / __bool__ - method. - * True: Most of constructs are True by default: - classes, functions, modules etc - * Uninferable: The inference engine is uncertain of the - node's value. - - :returns: The boolean value of this node. - :rtype: bool or Uninferable - """ - return util.Uninferable - - def op_precedence(self): - # Look up by class name or default to highest precedence - return OP_PRECEDENCE.get(self.__class__.__name__, len(OP_PRECEDENCE)) - - def op_left_associative(self): - # Everything is left associative except `**` and IfExp - return True - - -class Statement(NodeNG): - """Statement node adding a few attributes""" - - is_statement = True - """Whether this node indicates a statement. - - :type: bool - """ - - def next_sibling(self): - """The next sibling statement node. - - :returns: The next sibling statement node. - :rtype: NodeNG or None - """ - stmts = self.parent.child_sequence(self) - index = stmts.index(self) - try: - return stmts[index + 1] - except IndexError: - pass - - def previous_sibling(self): - """The previous sibling statement. - - :returns: The previous sibling statement node. - :rtype: NodeNG or None - """ - stmts = self.parent.child_sequence(self) - index = stmts.index(self) - if index >= 1: - return stmts[index - 1] - return None - - -class _BaseContainer( - mixins.ParentAssignTypeMixin, NodeNG, bases.Instance, metaclass=abc.ABCMeta -): - """Base class for Set, FrozenSet, Tuple and List.""" - - _astroid_fields = ("elts",) - - def __init__(self, lineno=None, col_offset=None, parent=None): - """ - :param lineno: The line that this node appears on in the source code. - :type lineno: int or None - - :param col_offset: The column that this node appears on in the - source code. - :type col_offset: int or None - - :param parent: The parent node in the syntax tree. - :type parent: NodeNG or None - """ - self.elts = [] - """The elements in the node. - - :type: list(NodeNG) - """ - - super().__init__(lineno, col_offset, parent) - - def postinit(self, elts): - """Do some setup after initialisation. - - :param elts: The list of elements the that node contains. - :type elts: list(NodeNG) - """ - self.elts = elts - - @classmethod - def from_elements(cls, elts=None): - """Create a node of this type from the given list of elements. - - :param elts: The list of elements that the node should contain. - :type elts: list(NodeNG) - - :returns: A new node containing the given elements. - :rtype: NodeNG - """ - node = cls() - if elts is None: - node.elts = [] - else: - node.elts = [const_factory(e) if _is_const(e) else e for e in elts] - return node - - def itered(self): - """An iterator over the elements this node contains. - - :returns: The contents of this node. - :rtype: iterable(NodeNG) - """ - return self.elts - - def bool_value(self, context=None): - """Determine the boolean value of this node. - - :returns: The boolean value of this node. - :rtype: bool or Uninferable - """ - return bool(self.elts) - - @abc.abstractmethod - def pytype(self): - """Get the name of the type that this node represents. - - :returns: The name of the type. - :rtype: str - """ - - def get_children(self): - yield from self.elts - - -class LookupMixIn: - """Mixin to look up a name in the right scope.""" - - @lru_cache(maxsize=None) - def lookup(self, name): - """Lookup where the given variable is assigned. - - The lookup starts from self's scope. If self is not a frame itself - and the name is found in the inner frame locals, statements will be - filtered to remove ignorable statements according to self's location. - - :param name: The name of the variable to find assignments for. - :type name: str - - :returns: The scope node and the list of assignments associated to the - given name according to the scope where it has been found (locals, - globals or builtin). - :rtype: tuple(str, list(NodeNG)) - """ - return self.scope().scope_lookup(self, name) - - def ilookup(self, name): - """Lookup the inferred values of the given variable. - - :param name: The variable name to find values for. - :type name: str - - :returns: The inferred values of the statements returned from - :meth:`lookup`. - :rtype: iterable - """ - frame, stmts = self.lookup(name) - context = contextmod.InferenceContext() - return bases._infer_stmts(stmts, context, frame) - - def _get_filtered_node_statements(self, nodes): - statements = [(node, node.statement()) for node in nodes] - # Next we check if we have ExceptHandlers that are parent - # of the underlying variable, in which case the last one survives - if len(statements) > 1 and all( - isinstance(stmt, ExceptHandler) for _, stmt in statements - ): - statements = [ - (node, stmt) for node, stmt in statements if stmt.parent_of(self) - ] - return statements - - def _filter_stmts(self, stmts, frame, offset): - """Filter the given list of statements to remove ignorable statements. - - If self is not a frame itself and the name is found in the inner - frame locals, statements will be filtered to remove ignorable - statements according to self's location. - - :param stmts: The statements to filter. - :type stmts: list(NodeNG) - - :param frame: The frame that all of the given statements belong to. - :type frame: NodeNG - - :param offset: The line offset to filter statements up to. - :type offset: int - - :returns: The filtered statements. - :rtype: list(NodeNG) - """ - # if offset == -1, my actual frame is not the inner frame but its parent - # - # class A(B): pass - # - # we need this to resolve B correctly - if offset == -1: - myframe = self.frame().parent.frame() - else: - myframe = self.frame() - # If the frame of this node is the same as the statement - # of this node, then the node is part of a class or - # a function definition and the frame of this node should be the - # the upper frame, not the frame of the definition. - # For more information why this is important, - # see Pylint issue #295. - # For example, for 'b', the statement is the same - # as the frame / scope: - # - # def test(b=1): - # ... - - if self.statement() is myframe and myframe.parent: - myframe = myframe.parent.frame() - mystmt = self.statement() - # line filtering if we are in the same frame - # - # take care node may be missing lineno information (this is the case for - # nodes inserted for living objects) - if myframe is frame and mystmt.fromlineno is not None: - assert mystmt.fromlineno is not None, mystmt - mylineno = mystmt.fromlineno + offset - else: - # disabling lineno filtering - mylineno = 0 - - _stmts = [] - _stmt_parents = [] - statements = self._get_filtered_node_statements(stmts) - - for node, stmt in statements: - # line filtering is on and we have reached our location, break - if stmt.fromlineno > mylineno > 0: - break - # Ignore decorators with the same name as the - # decorated function - # Fixes issue #375 - if mystmt is stmt and is_from_decorator(self): - continue - assert hasattr(node, "assign_type"), ( - node, - node.scope(), - node.scope().locals, - ) - assign_type = node.assign_type() - if node.has_base(self): - break - - _stmts, done = assign_type._get_filtered_stmts(self, node, _stmts, mystmt) - if done: - break - - optional_assign = assign_type.optional_assign - if optional_assign and assign_type.parent_of(self): - # we are inside a loop, loop var assignment is hiding previous - # assignment - _stmts = [node] - _stmt_parents = [stmt.parent] - continue - - if isinstance(assign_type, NamedExpr): - _stmts = [node] - continue - - # XXX comment various branches below!!! - try: - pindex = _stmt_parents.index(stmt.parent) - except ValueError: - pass - else: - # we got a parent index, this means the currently visited node - # is at the same block level as a previously visited node - if _stmts[pindex].assign_type().parent_of(assign_type): - # both statements are not at the same block level - continue - # if currently visited node is following previously considered - # assignment and both are not exclusive, we can drop the - # previous one. For instance in the following code :: - # - # if a: - # x = 1 - # else: - # x = 2 - # print x - # - # we can't remove neither x = 1 nor x = 2 when looking for 'x' - # of 'print x'; while in the following :: - # - # x = 1 - # x = 2 - # print x - # - # we can remove x = 1 when we see x = 2 - # - # moreover, on loop assignment types, assignment won't - # necessarily be done if the loop has no iteration, so we don't - # want to clear previous assignments if any (hence the test on - # optional_assign) - if not (optional_assign or are_exclusive(_stmts[pindex], node)): - if ( - # In case of partial function node, if the statement is different - # from the origin function then it can be deleted otherwise it should - # remain to be able to correctly infer the call to origin function. - not node.is_function - or node.qname() != "PartialFunction" - or node.name != _stmts[pindex].name - ): - del _stmt_parents[pindex] - del _stmts[pindex] - if isinstance(node, AssignName): - if not optional_assign and stmt.parent is mystmt.parent: - _stmts = [] - _stmt_parents = [] - elif isinstance(node, DelName): - _stmts = [] - _stmt_parents = [] - continue - if not are_exclusive(self, node): - _stmts.append(node) - _stmt_parents.append(stmt.parent) - return _stmts - - -# Name classes - - -class AssignName( - mixins.NoChildrenMixin, LookupMixIn, mixins.ParentAssignTypeMixin, NodeNG -): - """Variation of :class:`ast.Assign` representing assignment to a name. - - An :class:`AssignName` is the name of something that is assigned to. - This includes variables defined in a function signature or in a loop. - - >>> node = astroid.extract_node('variable = range(10)') - >>> node - - >>> list(node.get_children()) - [, ] - >>> list(node.get_children())[0].as_string() - 'variable' - """ - - _other_fields = ("name",) - - def __init__(self, name=None, lineno=None, col_offset=None, parent=None): - """ - :param name: The name that is assigned to. - :type name: str or None - - :param lineno: The line that this node appears on in the source code. - :type lineno: int or None - - :param col_offset: The column that this node appears on in the - source code. - :type col_offset: int or None - - :param parent: The parent node in the syntax tree. - :type parent: NodeNG or None - """ - self.name = name - """The name that is assigned to. - - :type: str or None - """ - - super().__init__(lineno, col_offset, parent) - - -class DelName( - mixins.NoChildrenMixin, LookupMixIn, mixins.ParentAssignTypeMixin, NodeNG -): - """Variation of :class:`ast.Delete` representing deletion of a name. - - A :class:`DelName` is the name of something that is deleted. - - >>> node = astroid.extract_node("del variable #@") - >>> list(node.get_children()) - [] - >>> list(node.get_children())[0].as_string() - 'variable' - """ - - _other_fields = ("name",) - - def __init__(self, name=None, lineno=None, col_offset=None, parent=None): - """ - :param name: The name that is being deleted. - :type name: str or None - - :param lineno: The line that this node appears on in the source code. - :type lineno: int or None - - :param col_offset: The column that this node appears on in the - source code. - :type col_offset: int or None - - :param parent: The parent node in the syntax tree. - :type parent: NodeNG or None - """ - self.name = name - """The name that is being deleted. - - :type: str or None - """ - - super().__init__(lineno, col_offset, parent) - - -class Name(mixins.NoChildrenMixin, LookupMixIn, NodeNG): - """Class representing an :class:`ast.Name` node. - - A :class:`Name` node is something that is named, but not covered by - :class:`AssignName` or :class:`DelName`. - - >>> node = astroid.extract_node('range(10)') - >>> node - - >>> list(node.get_children()) - [, ] - >>> list(node.get_children())[0].as_string() - 'range' - """ - - _other_fields = ("name",) - - def __init__(self, name=None, lineno=None, col_offset=None, parent=None): - """ - :param name: The name that this node refers to. - :type name: str or None - - :param lineno: The line that this node appears on in the source code. - :type lineno: int or None - - :param col_offset: The column that this node appears on in the - source code. - :type col_offset: int or None - - :param parent: The parent node in the syntax tree. - :type parent: NodeNG or None - """ - self.name = name - """The name that this node refers to. - - :type: str or None - """ - - super().__init__(lineno, col_offset, parent) - - def _get_name_nodes(self): - yield self - - for child_node in self.get_children(): - yield from child_node._get_name_nodes() - - -class Arguments(mixins.AssignTypeMixin, NodeNG): - """Class representing an :class:`ast.arguments` node. - - An :class:`Arguments` node represents that arguments in a - function definition. - - >>> node = astroid.extract_node('def foo(bar): pass') - >>> node - - >>> node.args - - """ - - # Python 3.4+ uses a different approach regarding annotations, - # each argument is a new class, _ast.arg, which exposes an - # 'annotation' attribute. In astroid though, arguments are exposed - # as is in the Arguments node and the only way to expose annotations - # is by using something similar with Python 3.3: - # - we expose 'varargannotation' and 'kwargannotation' of annotations - # of varargs and kwargs. - # - we expose 'annotation', a list with annotations for - # for each normal argument. If an argument doesn't have an - # annotation, its value will be None. - # pylint: disable=too-many-instance-attributes - _astroid_fields = ( - "args", - "defaults", - "kwonlyargs", - "posonlyargs", - "posonlyargs_annotations", - "kw_defaults", - "annotations", - "varargannotation", - "kwargannotation", - "kwonlyargs_annotations", - "type_comment_args", - "type_comment_kwonlyargs", - "type_comment_posonlyargs", - ) - varargannotation = None - """The type annotation for the variable length arguments. - - :type: NodeNG - """ - kwargannotation = None - """The type annotation for the variable length keyword arguments. - - :type: NodeNG - """ - - _other_fields = ("vararg", "kwarg") - - def __init__(self, vararg=None, kwarg=None, parent=None): - """ - :param vararg: The name of the variable length arguments. - :type vararg: str or None - - :param kwarg: The name of the variable length keyword arguments. - :type kwarg: str or None - - :param parent: The parent node in the syntax tree. - :type parent: NodeNG or None - """ - super().__init__(parent=parent) - self.vararg = vararg - """The name of the variable length arguments. - - :type: str or None - """ - - self.kwarg = kwarg - """The name of the variable length keyword arguments. - - :type: str or None - """ - - self.args = [] - """The names of the required arguments. - - :type: list(AssignName) - """ - - self.defaults = [] - """The default values for arguments that can be passed positionally. - - :type: list(NodeNG) - """ - - self.kwonlyargs = [] - """The keyword arguments that cannot be passed positionally. - - :type: list(AssignName) - """ - - self.posonlyargs = [] - """The arguments that can only be passed positionally. - - :type: list(AssignName) - """ - - self.kw_defaults = [] - """The default values for keyword arguments that cannot be passed positionally. - - :type: list(NodeNG) - """ - - self.annotations = [] - """The type annotations of arguments that can be passed positionally. - - :type: list(NodeNG) - """ - - self.posonlyargs_annotations = [] - """The type annotations of arguments that can only be passed positionally. - - :type: list(NodeNG) - """ - - self.kwonlyargs_annotations = [] - """The type annotations of arguments that cannot be passed positionally. - - :type: list(NodeNG) - """ - - self.type_comment_args = [] - """The type annotation, passed by a type comment, of each argument. - - If an argument does not have a type comment, - the value for that argument will be None. - - :type: list(NodeNG or None) - """ - - self.type_comment_kwonlyargs = [] - """The type annotation, passed by a type comment, of each keyword only argument. - - If an argument does not have a type comment, - the value for that argument will be None. - - :type: list(NodeNG or None) - """ - - self.type_comment_posonlyargs = [] - """The type annotation, passed by a type comment, of each positional argument. - - If an argument does not have a type comment, - the value for that argument will be None. - - :type: list(NodeNG or None) - """ - - # pylint: disable=too-many-arguments - def postinit( - self, - args, - defaults, - kwonlyargs, - kw_defaults, - annotations, - posonlyargs=None, - kwonlyargs_annotations=None, - posonlyargs_annotations=None, - varargannotation=None, - kwargannotation=None, - type_comment_args=None, - type_comment_kwonlyargs=None, - type_comment_posonlyargs=None, - ): - """Do some setup after initialisation. - - :param args: The names of the required arguments. - :type args: list(AssignName) - - :param defaults: The default values for arguments that can be passed - positionally. - :type defaults: list(NodeNG) - - :param kwonlyargs: The keyword arguments that cannot be passed - positionally. - :type kwonlyargs: list(AssignName) - - :param posonlyargs: The arguments that can only be passed - positionally. - :type kwonlyargs: list(AssignName) - - :param kw_defaults: The default values for keyword arguments that - cannot be passed positionally. - :type kw_defaults: list(NodeNG) - - :param annotations: The type annotations of arguments that can be - passed positionally. - :type annotations: list(NodeNG) - - :param kwonlyargs_annotations: The type annotations of arguments that - cannot be passed positionally. This should always be passed in - Python 3. - :type kwonlyargs_annotations: list(NodeNG) - - :param posonlyargs_annotations: The type annotations of arguments that - can only be passed positionally. This should always be passed in - Python 3. - :type posonlyargs_annotations: list(NodeNG) - - :param varargannotation: The type annotation for the variable length - arguments. - :type varargannotation: NodeNG - - :param kwargannotation: The type annotation for the variable length - keyword arguments. - :type kwargannotation: NodeNG - - :param type_comment_args: The type annotation, - passed by a type comment, of each argument. - :type type_comment_args: list(NodeNG or None) - - :param type_comment_args: The type annotation, - passed by a type comment, of each keyword only argument. - :type type_comment_args: list(NodeNG or None) - - :param type_comment_args: The type annotation, - passed by a type comment, of each positional argument. - :type type_comment_args: list(NodeNG or None) - """ - self.args = args - self.defaults = defaults - self.kwonlyargs = kwonlyargs - self.posonlyargs = posonlyargs - self.kw_defaults = kw_defaults - self.annotations = annotations - self.kwonlyargs_annotations = kwonlyargs_annotations - self.posonlyargs_annotations = posonlyargs_annotations - self.varargannotation = varargannotation - self.kwargannotation = kwargannotation - self.type_comment_args = type_comment_args - self.type_comment_kwonlyargs = type_comment_kwonlyargs - self.type_comment_posonlyargs = type_comment_posonlyargs - - # pylint: disable=too-many-arguments - - def _infer_name(self, frame, name): - if self.parent is frame: - return name - return None - - @decorators.cachedproperty - def fromlineno(self): - """The first line that this node appears on in the source code. - - :type: int or None - """ - lineno = super().fromlineno - return max(lineno, self.parent.fromlineno or 0) - - @decorators.cachedproperty - def arguments(self): - """Get all the arguments for this node, including positional only and positional and keyword""" - return list(itertools.chain((self.posonlyargs or ()), self.args or ())) - - def format_args(self): - """Get the arguments formatted as string. - - :returns: The formatted arguments. - :rtype: str - """ - result = [] - positional_only_defaults = [] - positional_or_keyword_defaults = self.defaults - if self.defaults: - args = self.args or [] - positional_or_keyword_defaults = self.defaults[-len(args) :] - positional_only_defaults = self.defaults[: len(self.defaults) - len(args)] - - if self.posonlyargs: - result.append( - _format_args( - self.posonlyargs, - positional_only_defaults, - self.posonlyargs_annotations, - ) - ) - result.append("/") - if self.args: - result.append( - _format_args( - self.args, - positional_or_keyword_defaults, - getattr(self, "annotations", None), - ) - ) - if self.vararg: - result.append("*%s" % self.vararg) - if self.kwonlyargs: - if not self.vararg: - result.append("*") - result.append( - _format_args( - self.kwonlyargs, self.kw_defaults, self.kwonlyargs_annotations - ) - ) - if self.kwarg: - result.append("**%s" % self.kwarg) - return ", ".join(result) - - def default_value(self, argname): - """Get the default value for an argument. - - :param argname: The name of the argument to get the default value for. - :type argname: str - - :raises NoDefault: If there is no default value defined for the - given argument. - """ - args = self.arguments - index = _find_arg(argname, args)[0] - if index is not None: - idx = index - (len(args) - len(self.defaults)) - if idx >= 0: - return self.defaults[idx] - index = _find_arg(argname, self.kwonlyargs)[0] - if index is not None and self.kw_defaults[index] is not None: - return self.kw_defaults[index] - raise exceptions.NoDefault(func=self.parent, name=argname) - - def is_argument(self, name): - """Check if the given name is defined in the arguments. - - :param name: The name to check for. - :type name: str - - :returns: True if the given name is defined in the arguments, - False otherwise. - :rtype: bool - """ - if name == self.vararg: - return True - if name == self.kwarg: - return True - return ( - self.find_argname(name, rec=True)[1] is not None - or self.kwonlyargs - and _find_arg(name, self.kwonlyargs, rec=True)[1] is not None - ) - - def find_argname(self, argname, rec=False): - """Get the index and :class:`AssignName` node for given name. - - :param argname: The name of the argument to search for. - :type argname: str - - :param rec: Whether or not to include arguments in unpacked tuples - in the search. - :type rec: bool - - :returns: The index and node for the argument. - :rtype: tuple(str or None, AssignName or None) - """ - if self.arguments: - return _find_arg(argname, self.arguments, rec) - return None, None - - def get_children(self): - yield from self.posonlyargs or () - - for elt in self.posonlyargs_annotations: - if elt is not None: - yield elt - - yield from self.args or () - - yield from self.defaults - yield from self.kwonlyargs - - for elt in self.kw_defaults: - if elt is not None: - yield elt - - for elt in self.annotations: - if elt is not None: - yield elt - - if self.varargannotation is not None: - yield self.varargannotation - - if self.kwargannotation is not None: - yield self.kwargannotation - - for elt in self.kwonlyargs_annotations: - if elt is not None: - yield elt - - -def _find_arg(argname, args, rec=False): - for i, arg in enumerate(args): - if isinstance(arg, Tuple): - if rec: - found = _find_arg(argname, arg.elts) - if found[0] is not None: - return found - elif arg.name == argname: - return i, arg - return None, None - - -def _format_args(args, defaults=None, annotations=None): - values = [] - if args is None: - return "" - if annotations is None: - annotations = [] - if defaults is not None: - default_offset = len(args) - len(defaults) - packed = itertools.zip_longest(args, annotations) - for i, (arg, annotation) in enumerate(packed): - if isinstance(arg, Tuple): - values.append("(%s)" % _format_args(arg.elts)) - else: - argname = arg.name - default_sep = "=" - if annotation is not None: - argname += ": " + annotation.as_string() - default_sep = " = " - values.append(argname) - - if defaults is not None and i >= default_offset: - if defaults[i - default_offset] is not None: - values[-1] += default_sep + defaults[i - default_offset].as_string() - return ", ".join(values) - - -class AssignAttr(mixins.ParentAssignTypeMixin, NodeNG): - """Variation of :class:`ast.Assign` representing assignment to an attribute. - - >>> node = astroid.extract_node('self.attribute = range(10)') - >>> node - - >>> list(node.get_children()) - [, ] - >>> list(node.get_children())[0].as_string() - 'self.attribute' - """ - - _astroid_fields = ("expr",) - _other_fields = ("attrname",) - expr = None - """What has the attribute that is being assigned to. - - :type: NodeNG or None - """ - - def __init__(self, attrname=None, lineno=None, col_offset=None, parent=None): - """ - :param attrname: The name of the attribute being assigned to. - :type attrname: str or None - - :param lineno: The line that this node appears on in the source code. - :type lineno: int or None - - :param col_offset: The column that this node appears on in the - source code. - :type col_offset: int or None - - :param parent: The parent node in the syntax tree. - :type parent: NodeNG or None - """ - self.attrname = attrname - """The name of the attribute being assigned to. - - :type: str or None - """ - - super().__init__(lineno, col_offset, parent) - - def postinit(self, expr=None): - """Do some setup after initialisation. - - :param expr: What has the attribute that is being assigned to. - :type expr: NodeNG or None - """ - self.expr = expr - - def get_children(self): - yield self.expr - - -class Assert(Statement): - """Class representing an :class:`ast.Assert` node. - - An :class:`Assert` node represents an assert statement. - - >>> node = astroid.extract_node('assert len(things) == 10, "Not enough things"') - >>> node - - """ - - _astroid_fields = ("test", "fail") - test = None - """The test that passes or fails the assertion. - - :type: NodeNG or None - """ - fail = None - """The message shown when the assertion fails. - - :type: NodeNG or None - """ - - def postinit(self, test=None, fail=None): - """Do some setup after initialisation. - - :param test: The test that passes or fails the assertion. - :type test: NodeNG or None - - :param fail: The message shown when the assertion fails. - :type fail: NodeNG or None - """ - self.fail = fail - self.test = test - - def get_children(self): - yield self.test - - if self.fail is not None: - yield self.fail - - -class Assign(mixins.AssignTypeMixin, Statement): - """Class representing an :class:`ast.Assign` node. - - An :class:`Assign` is a statement where something is explicitly - asssigned to. - - >>> node = astroid.extract_node('variable = range(10)') - >>> node - - """ - - _astroid_fields = ("targets", "value") - _other_other_fields = ("type_annotation",) - targets = None - """What is being assigned to. - - :type: list(NodeNG) or None - """ - value = None - """The value being assigned to the variables. - - :type: NodeNG or None - """ - type_annotation = None - """If present, this will contain the type annotation passed by a type comment - - :type: NodeNG or None - """ - - def postinit(self, targets=None, value=None, type_annotation=None): - """Do some setup after initialisation. - - :param targets: What is being assigned to. - :type targets: list(NodeNG) or None - - :param value: The value being assigned to the variables. - :type: NodeNG or None - """ - self.targets = targets - self.value = value - self.type_annotation = type_annotation - - def get_children(self): - yield from self.targets - - yield self.value - - @decorators.cached - def _get_assign_nodes(self): - return [self] + list(self.value._get_assign_nodes()) - - def _get_yield_nodes_skip_lambdas(self): - yield from self.value._get_yield_nodes_skip_lambdas() - - -class AnnAssign(mixins.AssignTypeMixin, Statement): - """Class representing an :class:`ast.AnnAssign` node. - - An :class:`AnnAssign` is an assignment with a type annotation. - - >>> node = astroid.extract_node('variable: List[int] = range(10)') - >>> node - - """ - - _astroid_fields = ("target", "annotation", "value") - _other_fields = ("simple",) - target = None - """What is being assigned to. - - :type: NodeNG or None - """ - annotation = None - """The type annotation of what is being assigned to. - - :type: NodeNG - """ - value = None - """The value being assigned to the variables. - - :type: NodeNG or None - """ - simple = None - """Whether :attr:`target` is a pure name or a complex statement. - - :type: int - """ - - def postinit(self, target, annotation, simple, value=None): - """Do some setup after initialisation. - - :param target: What is being assigned to. - :type target: NodeNG - - :param annotation: The type annotation of what is being assigned to. - :type: NodeNG - - :param simple: Whether :attr:`target` is a pure name - or a complex statement. - :type simple: int - - :param value: The value being assigned to the variables. - :type: NodeNG or None - """ - self.target = target - self.annotation = annotation - self.value = value - self.simple = simple - - def get_children(self): - yield self.target - yield self.annotation - - if self.value is not None: - yield self.value - - -class AugAssign(mixins.AssignTypeMixin, Statement): - """Class representing an :class:`ast.AugAssign` node. - - An :class:`AugAssign` is an assignment paired with an operator. - - >>> node = astroid.extract_node('variable += 1') - >>> node - - """ - - _astroid_fields = ("target", "value") - _other_fields = ("op",) - target = None - """What is being assigned to. - - :type: NodeNG or None - """ - value = None - """The value being assigned to the variable. - - :type: NodeNG or None - """ - - def __init__(self, op=None, lineno=None, col_offset=None, parent=None): - """ - :param op: The operator that is being combined with the assignment. - This includes the equals sign. - :type op: str or None - - :param lineno: The line that this node appears on in the source code. - :type lineno: int or None - - :param col_offset: The column that this node appears on in the - source code. - :type col_offset: int or None - - :param parent: The parent node in the syntax tree. - :type parent: NodeNG or None - """ - self.op = op - """The operator that is being combined with the assignment. - - This includes the equals sign. - - :type: str or None - """ - - super().__init__(lineno, col_offset, parent) - - def postinit(self, target=None, value=None): - """Do some setup after initialisation. - - :param target: What is being assigned to. - :type target: NodeNG or None - - :param value: The value being assigned to the variable. - :type: NodeNG or None - """ - self.target = target - self.value = value - - # This is set by inference.py - def _infer_augassign(self, context=None): - raise NotImplementedError - - def type_errors(self, context=None): - """Get a list of type errors which can occur during inference. - - Each TypeError is represented by a :class:`BadBinaryOperationMessage` , - which holds the original exception. - - :returns: The list of possible type errors. - :rtype: list(BadBinaryOperationMessage) - """ - try: - results = self._infer_augassign(context=context) - return [ - result - for result in results - if isinstance(result, util.BadBinaryOperationMessage) - ] - except exceptions.InferenceError: - return [] - - def get_children(self): - yield self.target - yield self.value - - -class Repr(NodeNG): - """Class representing an :class:`ast.Repr` node. - - A :class:`Repr` node represents the backtick syntax, - which is a deprecated alias for :func:`repr` removed in Python 3. - - >>> node = astroid.extract_node('`variable`') - >>> node - - """ - - _astroid_fields = ("value",) - value = None - """What is having :func:`repr` called on it. - - :type: NodeNG or None - """ - - def postinit(self, value=None): - """Do some setup after initialisation. - - :param value: What is having :func:`repr` called on it. - :type value: NodeNG or None - """ - self.value = value - - -class BinOp(NodeNG): - """Class representing an :class:`ast.BinOp` node. - - A :class:`BinOp` node is an application of a binary operator. - - >>> node = astroid.extract_node('a + b') - >>> node - - """ - - _astroid_fields = ("left", "right") - _other_fields = ("op",) - left = None - """What is being applied to the operator on the left side. - - :type: NodeNG or None - """ - right = None - """What is being applied to the operator on the right side. - - :type: NodeNG or None - """ - - def __init__(self, op=None, lineno=None, col_offset=None, parent=None): - """ - :param op: The operator. - :type: str or None - - :param lineno: The line that this node appears on in the source code. - :type lineno: int or None - - :param col_offset: The column that this node appears on in the - source code. - :type col_offset: int or None - - :param parent: The parent node in the syntax tree. - :type parent: NodeNG or None - """ - self.op = op - """The operator. - - :type: str or None - """ - - super().__init__(lineno, col_offset, parent) - - def postinit(self, left=None, right=None): - """Do some setup after initialisation. - - :param left: What is being applied to the operator on the left side. - :type left: NodeNG or None - - :param right: What is being applied to the operator on the right side. - :type right: NodeNG or None - """ - self.left = left - self.right = right - - # This is set by inference.py - def _infer_binop(self, context=None): - raise NotImplementedError - - def type_errors(self, context=None): - """Get a list of type errors which can occur during inference. - - Each TypeError is represented by a :class:`BadBinaryOperationMessage`, - which holds the original exception. - - :returns: The list of possible type errors. - :rtype: list(BadBinaryOperationMessage) - """ - try: - results = self._infer_binop(context=context) - return [ - result - for result in results - if isinstance(result, util.BadBinaryOperationMessage) - ] - except exceptions.InferenceError: - return [] - - def get_children(self): - yield self.left - yield self.right - - def op_precedence(self): - return OP_PRECEDENCE[self.op] - - def op_left_associative(self): - # 2**3**4 == 2**(3**4) - return self.op != "**" - - -class BoolOp(NodeNG): - """Class representing an :class:`ast.BoolOp` node. - - A :class:`BoolOp` is an application of a boolean operator. - - >>> node = astroid.extract_node('a and b') - >>> node - - """ - - _astroid_fields = ("values",) - _other_fields = ("op",) - values = None - """The values being applied to the operator. - - :type: list(NodeNG) or None - """ - - def __init__(self, op=None, lineno=None, col_offset=None, parent=None): - """ - :param op: The operator. - :type: str or None - - :param lineno: The line that this node appears on in the source code. - :type lineno: int or None - - :param col_offset: The column that this node appears on in the - source code. - :type col_offset: int or None - - :param parent: The parent node in the syntax tree. - :type parent: NodeNG or None - """ - self.op = op - """The operator. - - :type: str or None - """ - - super().__init__(lineno, col_offset, parent) - - def postinit(self, values=None): - """Do some setup after initialisation. - - :param values: The values being applied to the operator. - :type values: list(NodeNG) or None - """ - self.values = values - - def get_children(self): - yield from self.values - - def op_precedence(self): - return OP_PRECEDENCE[self.op] - - -class Break(mixins.NoChildrenMixin, Statement): - """Class representing an :class:`ast.Break` node. - - >>> node = astroid.extract_node('break') - >>> node - - """ - - -class Call(NodeNG): - """Class representing an :class:`ast.Call` node. - - A :class:`Call` node is a call to a function, method, etc. - - >>> node = astroid.extract_node('function()') - >>> node - - """ - - _astroid_fields = ("func", "args", "keywords") - func = None - """What is being called. - - :type: NodeNG or None - """ - args = None - """The positional arguments being given to the call. - - :type: list(NodeNG) or None - """ - keywords = None - """The keyword arguments being given to the call. - - :type: list(NodeNG) or None - """ - - def postinit(self, func=None, args=None, keywords=None): - """Do some setup after initialisation. - - :param func: What is being called. - :type func: NodeNG or None - - :param args: The positional arguments being given to the call. - :type args: list(NodeNG) or None - - :param keywords: The keyword arguments being given to the call. - :type keywords: list(NodeNG) or None - """ - self.func = func - self.args = args - self.keywords = keywords - - @property - def starargs(self): - """The positional arguments that unpack something. - - :type: list(Starred) - """ - args = self.args or [] - return [arg for arg in args if isinstance(arg, Starred)] - - @property - def kwargs(self): - """The keyword arguments that unpack something. - - :type: list(Keyword) - """ - keywords = self.keywords or [] - return [keyword for keyword in keywords if keyword.arg is None] - - def get_children(self): - yield self.func - - yield from self.args - - yield from self.keywords or () - - -class Compare(NodeNG): - """Class representing an :class:`ast.Compare` node. - - A :class:`Compare` node indicates a comparison. - - >>> node = astroid.extract_node('a <= b <= c') - >>> node - - >>> node.ops - [('<=', ), ('<=', )] - """ - - _astroid_fields = ("left", "ops") - left = None - """The value at the left being applied to a comparison operator. - - :type: NodeNG or None - """ - ops = None - """The remainder of the operators and their relevant right hand value. - - :type: list(tuple(str, NodeNG)) or None - """ - - def postinit(self, left=None, ops=None): - """Do some setup after initialisation. - - :param left: The value at the left being applied to a comparison - operator. - :type left: NodeNG or None - - :param ops: The remainder of the operators - and their relevant right hand value. - :type ops: list(tuple(str, NodeNG)) or None - """ - self.left = left - self.ops = ops - - def get_children(self): - """Get the child nodes below this node. - - Overridden to handle the tuple fields and skip returning the operator - strings. - - :returns: The children. - :rtype: iterable(NodeNG) - """ - yield self.left - for _, comparator in self.ops: - yield comparator # we don't want the 'op' - - def last_child(self): - """An optimized version of list(get_children())[-1] - - :returns: The last child. - :rtype: NodeNG - """ - # XXX maybe if self.ops: - return self.ops[-1][1] - # return self.left - - -class Comprehension(NodeNG): - """Class representing an :class:`ast.comprehension` node. - - A :class:`Comprehension` indicates the loop inside any type of - comprehension including generator expressions. - - >>> node = astroid.extract_node('[x for x in some_values]') - >>> list(node.get_children()) - [, ] - >>> list(node.get_children())[1].as_string() - 'for x in some_values' - """ - - _astroid_fields = ("target", "iter", "ifs") - _other_fields = ("is_async",) - target = None - """What is assigned to by the comprehension. - - :type: NodeNG or None - """ - iter = None - """What is iterated over by the comprehension. - - :type: NodeNG or None - """ - ifs = None - """The contents of any if statements that filter the comprehension. - - :type: list(NodeNG) or None - """ - is_async = None - """Whether this is an asynchronous comprehension or not. - - :type: bool or None - """ - - def __init__(self, parent=None): - """ - :param parent: The parent node in the syntax tree. - :type parent: NodeNG or None - """ - super().__init__() - self.parent = parent - - # pylint: disable=redefined-builtin; same name as builtin ast module. - def postinit(self, target=None, iter=None, ifs=None, is_async=None): - """Do some setup after initialisation. - - :param target: What is assigned to by the comprehension. - :type target: NodeNG or None - - :param iter: What is iterated over by the comprehension. - :type iter: NodeNG or None - - :param ifs: The contents of any if statements that filter - the comprehension. - :type ifs: list(NodeNG) or None - - :param is_async: Whether this is an asynchronous comprehension or not. - :type: bool or None - """ - self.target = target - self.iter = iter - self.ifs = ifs - self.is_async = is_async - - optional_assign = True - """Whether this node optionally assigns a variable. - - :type: bool - """ - - def assign_type(self): - """The type of assignment that this node performs. - - :returns: The assignment type. - :rtype: NodeNG - """ - return self - - def _get_filtered_stmts(self, lookup_node, node, stmts, mystmt): - """method used in filter_stmts""" - if self is mystmt: - if isinstance(lookup_node, (Const, Name)): - return [lookup_node], True - - elif self.statement() is mystmt: - # original node's statement is the assignment, only keeps - # current node (gen exp, list comp) - - return [node], True - - return stmts, False - - def get_children(self): - yield self.target - yield self.iter - - yield from self.ifs - - -class Const(mixins.NoChildrenMixin, NodeNG, bases.Instance): - """Class representing any constant including num, str, bool, None, bytes. - - >>> node = astroid.extract_node('(5, "This is a string.", True, None, b"bytes")') - >>> node - - >>> list(node.get_children()) - [, - , - , - , - ] - """ - - _other_fields = ("value",) - - def __init__(self, value, lineno=None, col_offset=None, parent=None): - """ - :param value: The value that the constant represents. - :type value: object - - :param lineno: The line that this node appears on in the source code. - :type lineno: int or None - - :param col_offset: The column that this node appears on in the - source code. - :type col_offset: int or None - - :param parent: The parent node in the syntax tree. - :type parent: NodeNG or None - """ - self.value = value - """The value that the constant represents. - - :type: object - """ - - super().__init__(lineno, col_offset, parent) - - def __getattr__(self, name): - # This is needed because of Proxy's __getattr__ method. - # Calling object.__new__ on this class without calling - # __init__ would result in an infinite loop otherwise - # since __getattr__ is called when an attribute doesn't - # exist and self._proxied indirectly calls self.value - # and Proxy __getattr__ calls self.value - if name == "value": - raise AttributeError - return super().__getattr__(name) - - def getitem(self, index, context=None): - """Get an item from this node if subscriptable. - - :param index: The node to use as a subscript index. - :type index: Const or Slice - - :raises AstroidTypeError: When the given index cannot be used as a - subscript index, or if this node is not subscriptable. - """ - if isinstance(index, Const): - index_value = index.value - elif isinstance(index, Slice): - index_value = _infer_slice(index, context=context) - - else: - raise exceptions.AstroidTypeError( - "Could not use type {} as subscript index".format(type(index)) - ) - - try: - if isinstance(self.value, (str, bytes)): - return Const(self.value[index_value]) - except IndexError as exc: - raise exceptions.AstroidIndexError( - message="Index {index!r} out of range", - node=self, - index=index, - context=context, - ) from exc - except TypeError as exc: - raise exceptions.AstroidTypeError( - message="Type error {error!r}", node=self, index=index, context=context - ) from exc - - raise exceptions.AstroidTypeError("%r (value=%s)" % (self, self.value)) - - def has_dynamic_getattr(self): - """Check if the node has a custom __getattr__ or __getattribute__. - - :returns: True if the class has a custom - __getattr__ or __getattribute__, False otherwise. - For a :class:`Const` this is always ``False``. - :rtype: bool - """ - return False - - def itered(self): - """An iterator over the elements this node contains. - - :returns: The contents of this node. - :rtype: iterable(Const) - - :raises TypeError: If this node does not represent something that is iterable. - """ - if isinstance(self.value, str): - return [const_factory(elem) for elem in self.value] - raise TypeError("Cannot iterate over type {!r}".format(type(self.value))) - - def pytype(self): - """Get the name of the type that this node represents. - - :returns: The name of the type. - :rtype: str - """ - return self._proxied.qname() - - def bool_value(self, context=None): - """Determine the boolean value of this node. - - :returns: The boolean value of this node. - :rtype: bool - """ - return bool(self.value) - - -class Continue(mixins.NoChildrenMixin, Statement): - """Class representing an :class:`ast.Continue` node. - - >>> node = astroid.extract_node('continue') - >>> node - - """ - - -class Decorators(NodeNG): - """A node representing a list of decorators. - - A :class:`Decorators` is the decorators that are applied to - a method or function. - - >>> node = astroid.extract_node(''' - @property - def my_property(self): - return 3 - ''') - >>> node - - >>> list(node.get_children())[0] - - """ - - _astroid_fields = ("nodes",) - nodes = None - """The decorators that this node contains. - - :type: list(Name or Call) or None - """ - - def postinit(self, nodes): - """Do some setup after initialisation. - - :param nodes: The decorators that this node contains. - :type nodes: list(Name or Call) - """ - self.nodes = nodes - - def scope(self): - """The first parent node defining a new scope. - - :returns: The first parent scope node. - :rtype: Module or FunctionDef or ClassDef or Lambda or GenExpr - """ - # skip the function node to go directly to the upper level scope - return self.parent.parent.scope() - - def get_children(self): - yield from self.nodes - - -class DelAttr(mixins.ParentAssignTypeMixin, NodeNG): - """Variation of :class:`ast.Delete` representing deletion of an attribute. - - >>> node = astroid.extract_node('del self.attr') - >>> node - - >>> list(node.get_children())[0] - - """ - - _astroid_fields = ("expr",) - _other_fields = ("attrname",) - expr = None - """The name that this node represents. - - :type: Name or None - """ - - def __init__(self, attrname=None, lineno=None, col_offset=None, parent=None): - """ - :param attrname: The name of the attribute that is being deleted. - :type attrname: str or None - - :param lineno: The line that this node appears on in the source code. - :type lineno: int or None - - :param col_offset: The column that this node appears on in the - source code. - :type col_offset: int or None - - :param parent: The parent node in the syntax tree. - :type parent: NodeNG or None - """ - self.attrname = attrname - """The name of the attribute that is being deleted. - - :type: str or None - """ - - super().__init__(lineno, col_offset, parent) - - def postinit(self, expr=None): - """Do some setup after initialisation. - - :param expr: The name that this node represents. - :type expr: Name or None - """ - self.expr = expr - - def get_children(self): - yield self.expr - - -class Delete(mixins.AssignTypeMixin, Statement): - """Class representing an :class:`ast.Delete` node. - - A :class:`Delete` is a ``del`` statement this is deleting something. - - >>> node = astroid.extract_node('del self.attr') - >>> node - - """ - - _astroid_fields = ("targets",) - targets = None - """What is being deleted. - - :type: list(NodeNG) or None - """ - - def postinit(self, targets=None): - """Do some setup after initialisation. - - :param targets: What is being deleted. - :type targets: list(NodeNG) or None - """ - self.targets = targets - - def get_children(self): - yield from self.targets - - -class Dict(NodeNG, bases.Instance): - """Class representing an :class:`ast.Dict` node. - - A :class:`Dict` is a dictionary that is created with ``{}`` syntax. - - >>> node = astroid.extract_node('{1: "1"}') - >>> node - - """ - - _astroid_fields = ("items",) - - def __init__(self, lineno=None, col_offset=None, parent=None): - """ - :param lineno: The line that this node appears on in the source code. - :type lineno: int or None - - :param col_offset: The column that this node appears on in the - source code. - :type col_offset: int or None - - :param parent: The parent node in the syntax tree. - :type parent: NodeNG or None - """ - self.items = [] - """The key-value pairs contained in the dictionary. - - :type: list(tuple(NodeNG, NodeNG)) - """ - - super().__init__(lineno, col_offset, parent) - - def postinit(self, items): - """Do some setup after initialisation. - - :param items: The key-value pairs contained in the dictionary. - :type items: list(tuple(NodeNG, NodeNG)) - """ - self.items = items - - @classmethod - def from_elements(cls, items=None): - """Create a :class:`Dict` of constants from a live dictionary. - - :param items: The items to store in the node. - :type items: dict - - :returns: The created dictionary node. - :rtype: Dict - """ - node = cls() - if items is None: - node.items = [] - else: - node.items = [ - (const_factory(k), const_factory(v) if _is_const(v) else v) - for k, v in items.items() - # The keys need to be constants - if _is_const(k) - ] - return node - - def pytype(self): - """Get the name of the type that this node represents. - - :returns: The name of the type. - :rtype: str - """ - return "%s.dict" % BUILTINS - - def get_children(self): - """Get the key and value nodes below this node. - - Children are returned in the order that they are defined in the source - code, key first then the value. - - :returns: The children. - :rtype: iterable(NodeNG) - """ - for key, value in self.items: - yield key - yield value - - def last_child(self): - """An optimized version of list(get_children())[-1] - - :returns: The last child, or None if no children exist. - :rtype: NodeNG or None - """ - if self.items: - return self.items[-1][1] - return None - - def itered(self): - """An iterator over the keys this node contains. - - :returns: The keys of this node. - :rtype: iterable(NodeNG) - """ - return [key for (key, _) in self.items] - - def getitem(self, index, context=None): - """Get an item from this node. - - :param index: The node to use as a subscript index. - :type index: Const or Slice - - :raises AstroidTypeError: When the given index cannot be used as a - subscript index, or if this node is not subscriptable. - :raises AstroidIndexError: If the given index does not exist in the - dictionary. - """ - for key, value in self.items: - # TODO(cpopa): no support for overriding yet, {1:2, **{1: 3}}. - if isinstance(key, DictUnpack): - try: - return value.getitem(index, context) - except (exceptions.AstroidTypeError, exceptions.AstroidIndexError): - continue - for inferredkey in key.infer(context): - if inferredkey is util.Uninferable: - continue - if isinstance(inferredkey, Const) and isinstance(index, Const): - if inferredkey.value == index.value: - return value - - raise exceptions.AstroidIndexError(index) - - def bool_value(self, context=None): - """Determine the boolean value of this node. - - :returns: The boolean value of this node. - :rtype: bool - """ - return bool(self.items) - - -class Expr(Statement): - """Class representing an :class:`ast.Expr` node. - - An :class:`Expr` is any expression that does not have its value used or - stored. - - >>> node = astroid.extract_node('method()') - >>> node - - >>> node.parent - - """ - - _astroid_fields = ("value",) - value = None - """What the expression does. - - :type: NodeNG or None - """ - - def postinit(self, value=None): - """Do some setup after initialisation. - - :param value: What the expression does. - :type value: NodeNG or None - """ - self.value = value - - def get_children(self): - yield self.value - - def _get_yield_nodes_skip_lambdas(self): - if not self.value.is_lambda: - yield from self.value._get_yield_nodes_skip_lambdas() - - -class Ellipsis(mixins.NoChildrenMixin, NodeNG): # pylint: disable=redefined-builtin - """Class representing an :class:`ast.Ellipsis` node. - - An :class:`Ellipsis` is the ``...`` syntax. - - >>> node = astroid.extract_node('...') - >>> node - - """ - - def bool_value(self, context=None): - """Determine the boolean value of this node. - - :returns: The boolean value of this node. - For an :class:`Ellipsis` this is always ``True``. - :rtype: bool - """ - return True - - -class EmptyNode(mixins.NoChildrenMixin, NodeNG): - """Holds an arbitrary object in the :attr:`LocalsDictNodeNG.locals`.""" - - object = None - - -class ExceptHandler(mixins.MultiLineBlockMixin, mixins.AssignTypeMixin, Statement): - """Class representing an :class:`ast.ExceptHandler`. node. - - An :class:`ExceptHandler` is an ``except`` block on a try-except. - - >>> node = astroid.extract_node(''' - try: - do_something() - except Exception as error: - print("Error!") - ''') - >>> node - - >>> >>> node.handlers - [] - """ - - _astroid_fields = ("type", "name", "body") - _multi_line_block_fields = ("body",) - type = None - """The types that the block handles. - - :type: Tuple or NodeNG or None - """ - name = None - """The name that the caught exception is assigned to. - - :type: AssignName or None - """ - body = None - """The contents of the block. - - :type: list(NodeNG) or None - """ - - def get_children(self): - if self.type is not None: - yield self.type - - if self.name is not None: - yield self.name - - yield from self.body - - # pylint: disable=redefined-builtin; had to use the same name as builtin ast module. - def postinit(self, type=None, name=None, body=None): - """Do some setup after initialisation. - - :param type: The types that the block handles. - :type type: Tuple or NodeNG or None - - :param name: The name that the caught exception is assigned to. - :type name: AssignName or None - - :param body:The contents of the block. - :type body: list(NodeNG) or None - """ - self.type = type - self.name = name - self.body = body - - @decorators.cachedproperty - def blockstart_tolineno(self): - """The line on which the beginning of this block ends. - - :type: int - """ - if self.name: - return self.name.tolineno - if self.type: - return self.type.tolineno - return self.lineno - - def catch(self, exceptions): # pylint: disable=redefined-outer-name - """Check if this node handles any of the given exceptions. - - If ``exceptions`` is empty, this will default to ``True``. - - :param exceptions: The name of the exceptions to check for. - :type exceptions: list(str) - """ - if self.type is None or exceptions is None: - return True - for node in self.type._get_name_nodes(): - if node.name in exceptions: - return True - return False - - -class Exec(Statement): - """Class representing the ``exec`` statement. - - >>> node = astroid.extract_node('exec "True"') - >>> node - - """ - - _astroid_fields = ("expr", "globals", "locals") - expr = None - """The expression to be executed. - - :type: NodeNG or None - """ - globals = None - """The globals dictionary to execute with. - - :type: NodeNG or None - """ - locals = None - """The locals dictionary to execute with. - - :type: NodeNG or None - """ - - # pylint: disable=redefined-builtin; had to use the same name as builtin ast module. - def postinit(self, expr=None, globals=None, locals=None): - """Do some setup after initialisation. - - :param expr: The expression to be executed. - :type expr: NodeNG or None - - :param globals:The globals dictionary to execute with. - :type globals: NodeNG or None - - :param locals: The locals dictionary to execute with. - :type locals: NodeNG or None - """ - self.expr = expr - self.globals = globals - self.locals = locals - - -class ExtSlice(NodeNG): - """Class representing an :class:`ast.ExtSlice` node. - - An :class:`ExtSlice` is a complex slice expression. - - >>> node = astroid.extract_node('l[1:3, 5]') - >>> node - - >>> node.slice - - """ - - _astroid_fields = ("dims",) - dims = None - """The simple dimensions that form the complete slice. - - :type: list(NodeNG) or None - """ - - def postinit(self, dims=None): - """Do some setup after initialisation. - - :param dims: The simple dimensions that form the complete slice. - :type dims: list(NodeNG) or None - """ - self.dims = dims - - -class For( - mixins.MultiLineBlockMixin, - mixins.BlockRangeMixIn, - mixins.AssignTypeMixin, - Statement, -): - """Class representing an :class:`ast.For` node. - - >>> node = astroid.extract_node('for thing in things: print(thing)') - >>> node - - """ - - _astroid_fields = ("target", "iter", "body", "orelse") - _other_other_fields = ("type_annotation",) - _multi_line_block_fields = ("body", "orelse") - target = None - """What the loop assigns to. - - :type: NodeNG or None - """ - iter = None - """What the loop iterates over. - - :type: NodeNG or None - """ - body = None - """The contents of the body of the loop. - - :type: list(NodeNG) or None - """ - orelse = None - """The contents of the ``else`` block of the loop. - - :type: list(NodeNG) or None - """ - type_annotation = None - """If present, this will contain the type annotation passed by a type comment - - :type: NodeNG or None - """ - - # pylint: disable=redefined-builtin; had to use the same name as builtin ast module. - def postinit( - self, target=None, iter=None, body=None, orelse=None, type_annotation=None - ): - """Do some setup after initialisation. - - :param target: What the loop assigns to. - :type target: NodeNG or None - - :param iter: What the loop iterates over. - :type iter: NodeNG or None - - :param body: The contents of the body of the loop. - :type body: list(NodeNG) or None - - :param orelse: The contents of the ``else`` block of the loop. - :type orelse: list(NodeNG) or None - """ - self.target = target - self.iter = iter - self.body = body - self.orelse = orelse - self.type_annotation = type_annotation - - optional_assign = True - """Whether this node optionally assigns a variable. - - This is always ``True`` for :class:`For` nodes. - - :type: bool - """ - - @decorators.cachedproperty - def blockstart_tolineno(self): - """The line on which the beginning of this block ends. - - :type: int - """ - return self.iter.tolineno - - def get_children(self): - yield self.target - yield self.iter - - yield from self.body - yield from self.orelse - - -class AsyncFor(For): - """Class representing an :class:`ast.AsyncFor` node. - - An :class:`AsyncFor` is an asynchronous :class:`For` built with - the ``async`` keyword. - - >>> node = astroid.extract_node(''' - async def func(things): - async for thing in things: - print(thing) - ''') - >>> node - - >>> node.body[0] - - """ - - -class Await(NodeNG): - """Class representing an :class:`ast.Await` node. - - An :class:`Await` is the ``await`` keyword. - - >>> node = astroid.extract_node(''' - async def func(things): - await other_func() - ''') - >>> node - - >>> node.body[0] - - >>> list(node.body[0].get_children())[0] - - """ - - _astroid_fields = ("value",) - value = None - """What to wait for. - - :type: NodeNG or None - """ - - def postinit(self, value=None): - """Do some setup after initialisation. - - :param value: What to wait for. - :type value: NodeNG or None - """ - self.value = value - - def get_children(self): - yield self.value - - -class ImportFrom(mixins.NoChildrenMixin, mixins.ImportFromMixin, Statement): - """Class representing an :class:`ast.ImportFrom` node. - - >>> node = astroid.extract_node('from my_package import my_module') - >>> node - - """ - - _other_fields = ("modname", "names", "level") - - def __init__( - self, fromname, names, level=0, lineno=None, col_offset=None, parent=None - ): - """ - :param fromname: The module that is being imported from. - :type fromname: str or None - - :param names: What is being imported from the module. - :type names: list(tuple(str, str or None)) - - :param level: The level of relative import. - :type level: int - - :param lineno: The line that this node appears on in the source code. - :type lineno: int or None - - :param col_offset: The column that this node appears on in the - source code. - :type col_offset: int or None - - :param parent: The parent node in the syntax tree. - :type parent: NodeNG or None - """ - self.modname = fromname - """The module that is being imported from. - - This is ``None`` for relative imports. - - :type: str or None - """ - - self.names = names - """What is being imported from the module. - - Each entry is a :class:`tuple` of the name being imported, - and the alias that the name is assigned to (if any). - - :type: list(tuple(str, str or None)) - """ - - self.level = level - """The level of relative import. - - Essentially this is the number of dots in the import. - This is always 0 for absolute imports. - - :type: int - """ - - super().__init__(lineno, col_offset, parent) - - -class Attribute(NodeNG): - """Class representing an :class:`ast.Attribute` node.""" - - _astroid_fields = ("expr",) - _other_fields = ("attrname",) - expr = None - """The name that this node represents. - - :type: Name or None - """ - - def __init__(self, attrname=None, lineno=None, col_offset=None, parent=None): - """ - :param attrname: The name of the attribute. - :type attrname: str or None - - :param lineno: The line that this node appears on in the source code. - :type lineno: int or None - - :param col_offset: The column that this node appears on in the - source code. - :type col_offset: int or None - - :param parent: The parent node in the syntax tree. - :type parent: NodeNG or None - """ - self.attrname = attrname - """The name of the attribute. - - :type: str or None - """ - - super().__init__(lineno, col_offset, parent) - - def postinit(self, expr=None): - """Do some setup after initialisation. - - :param expr: The name that this node represents. - :type expr: Name or None - """ - self.expr = expr - - def get_children(self): - yield self.expr - - -class Global(mixins.NoChildrenMixin, Statement): - """Class representing an :class:`ast.Global` node. - - >>> node = astroid.extract_node('global a_global') - >>> node - - """ - - _other_fields = ("names",) - - def __init__(self, names, lineno=None, col_offset=None, parent=None): - """ - :param names: The names being declared as global. - :type names: list(str) - - :param lineno: The line that this node appears on in the source code. - :type lineno: int or None - - :param col_offset: The column that this node appears on in the - source code. - :type col_offset: int or None - - :param parent: The parent node in the syntax tree. - :type parent: NodeNG or None - """ - self.names = names - """The names being declared as global. - - :type: list(str) - """ - - super().__init__(lineno, col_offset, parent) - - def _infer_name(self, frame, name): - return name - - -class If(mixins.MultiLineBlockMixin, mixins.BlockRangeMixIn, Statement): - """Class representing an :class:`ast.If` node. - - >>> node = astroid.extract_node('if condition: print(True)') - >>> node - - """ - - _astroid_fields = ("test", "body", "orelse") - _multi_line_block_fields = ("body", "orelse") - test = None - """The condition that the statement tests. - - :type: NodeNG or None - """ - body = None - """The contents of the block. - - :type: list(NodeNG) or None - """ - orelse = None - """The contents of the ``else`` block. - - :type: list(NodeNG) or None - """ - - def postinit(self, test=None, body=None, orelse=None): - """Do some setup after initialisation. - - :param test: The condition that the statement tests. - :type test: NodeNG or None - - :param body: The contents of the block. - :type body: list(NodeNG) or None - - :param orelse: The contents of the ``else`` block. - :type orelse: list(NodeNG) or None - """ - self.test = test - self.body = body - self.orelse = orelse - - @decorators.cachedproperty - def blockstart_tolineno(self): - """The line on which the beginning of this block ends. - - :type: int - """ - return self.test.tolineno - - def block_range(self, lineno): - """Get a range from the given line number to where this node ends. - - :param lineno: The line number to start the range at. - :type lineno: int - - :returns: The range of line numbers that this node belongs to, - starting at the given line number. - :rtype: tuple(int, int) - """ - if lineno == self.body[0].fromlineno: - return lineno, lineno - if lineno <= self.body[-1].tolineno: - return lineno, self.body[-1].tolineno - return self._elsed_block_range(lineno, self.orelse, self.body[0].fromlineno - 1) - - def get_children(self): - yield self.test - - yield from self.body - yield from self.orelse - - def has_elif_block(self): - return len(self.orelse) == 1 and isinstance(self.orelse[0], If) - - -class IfExp(NodeNG): - """Class representing an :class:`ast.IfExp` node. - - >>> node = astroid.extract_node('value if condition else other') - >>> node - - """ - - _astroid_fields = ("test", "body", "orelse") - test = None - """The condition that the statement tests. - - :type: NodeNG or None - """ - body = None - """The contents of the block. - - :type: list(NodeNG) or None - """ - orelse = None - """The contents of the ``else`` block. - - :type: list(NodeNG) or None - """ - - def postinit(self, test=None, body=None, orelse=None): - """Do some setup after initialisation. - - :param test: The condition that the statement tests. - :type test: NodeNG or None - - :param body: The contents of the block. - :type body: list(NodeNG) or None - - :param orelse: The contents of the ``else`` block. - :type orelse: list(NodeNG) or None - """ - self.test = test - self.body = body - self.orelse = orelse - - def get_children(self): - yield self.test - yield self.body - yield self.orelse - - def op_left_associative(self): - # `1 if True else 2 if False else 3` is parsed as - # `1 if True else (2 if False else 3)` - return False - - -class Import(mixins.NoChildrenMixin, mixins.ImportFromMixin, Statement): - """Class representing an :class:`ast.Import` node. - - >>> node = astroid.extract_node('import astroid') - >>> node - - """ - - _other_fields = ("names",) - - def __init__(self, names=None, lineno=None, col_offset=None, parent=None): - """ - :param names: The names being imported. - :type names: list(tuple(str, str or None)) or None - - :param lineno: The line that this node appears on in the source code. - :type lineno: int or None - - :param col_offset: The column that this node appears on in the - source code. - :type col_offset: int or None - - :param parent: The parent node in the syntax tree. - :type parent: NodeNG or None - """ - self.names = names - """The names being imported. - - Each entry is a :class:`tuple` of the name being imported, - and the alias that the name is assigned to (if any). - - :type: list(tuple(str, str or None)) or None - """ - - super().__init__(lineno, col_offset, parent) - - -class Index(NodeNG): - """Class representing an :class:`ast.Index` node. - - An :class:`Index` is a simple subscript. - - >>> node = astroid.extract_node('things[1]') - >>> node - - >>> node.slice - - """ - - _astroid_fields = ("value",) - value = None - """The value to subscript with. - - :type: NodeNG or None - """ - - def postinit(self, value=None): - """Do some setup after initialisation. - - :param value: The value to subscript with. - :type value: NodeNG or None - """ - self.value = value - - def get_children(self): - yield self.value - - -class Keyword(NodeNG): - """Class representing an :class:`ast.keyword` node. - - >>> node = astroid.extract_node('function(a_kwarg=True)') - >>> node - - >>> node.keywords - [] - """ - - _astroid_fields = ("value",) - _other_fields = ("arg",) - value = None - """The value being assigned to the keyword argument. - - :type: NodeNG or None - """ - - def __init__(self, arg=None, lineno=None, col_offset=None, parent=None): - """ - :param arg: The argument being assigned to. - :type arg: Name or None - - :param lineno: The line that this node appears on in the source code. - :type lineno: int or None - - :param col_offset: The column that this node appears on in the - source code. - :type col_offset: int or None - - :param parent: The parent node in the syntax tree. - :type parent: NodeNG or None - """ - self.arg = arg - """The argument being assigned to. - - :type: Name or None - """ - - super().__init__(lineno, col_offset, parent) - - def postinit(self, value=None): - """Do some setup after initialisation. - - :param value: The value being assigned to the ketword argument. - :type value: NodeNG or None - """ - self.value = value - - def get_children(self): - yield self.value - - -class List(_BaseContainer): - """Class representing an :class:`ast.List` node. - - >>> node = astroid.extract_node('[1, 2, 3]') - >>> node - - """ - - _other_fields = ("ctx",) - - def __init__(self, ctx=None, lineno=None, col_offset=None, parent=None): - """ - :param ctx: Whether the list is assigned to or loaded from. - :type ctx: Context or None - - :param lineno: The line that this node appears on in the source code. - :type lineno: int or None - - :param col_offset: The column that this node appears on in the - source code. - :type col_offset: int or None - - :param parent: The parent node in the syntax tree. - :type parent: NodeNG or None - """ - self.ctx = ctx - """Whether the list is assigned to or loaded from. - - :type: Context or None - """ - - super().__init__(lineno, col_offset, parent) - - def pytype(self): - """Get the name of the type that this node represents. - - :returns: The name of the type. - :rtype: str - """ - return "%s.list" % BUILTINS - - def getitem(self, index, context=None): - """Get an item from this node. - - :param index: The node to use as a subscript index. - :type index: Const or Slice - """ - return _container_getitem(self, self.elts, index, context=context) - - -class Nonlocal(mixins.NoChildrenMixin, Statement): - """Class representing an :class:`ast.Nonlocal` node. - - >>> node = astroid.extract_node(''' - def function(): - nonlocal var - ''') - >>> node - - >>> node.body[0] - - """ - - _other_fields = ("names",) - - def __init__(self, names, lineno=None, col_offset=None, parent=None): - """ - :param names: The names being declared as not local. - :type names: list(str) - - :param lineno: The line that this node appears on in the source code. - :type lineno: int or None - - :param col_offset: The column that this node appears on in the - source code. - :type col_offset: int or None - - :param parent: The parent node in the syntax tree. - :type parent: NodeNG or None - """ - self.names = names - """The names being declared as not local. - - :type: list(str) - """ - - super().__init__(lineno, col_offset, parent) - - def _infer_name(self, frame, name): - return name - - -class Pass(mixins.NoChildrenMixin, Statement): - """Class representing an :class:`ast.Pass` node. - - >>> node = astroid.extract_node('pass') - >>> node - - """ - - -class Print(Statement): - """Class representing an :class:`ast.Print` node. - - >>> node = astroid.extract_node('print "A message"') - >>> node - - """ - - _astroid_fields = ("dest", "values") - dest = None - """Where to print to. - - :type: NodeNG or None - """ - values = None - """What to print. - - :type: list(NodeNG) or None - """ - - def __init__(self, nl=None, lineno=None, col_offset=None, parent=None): - """ - :param nl: Whether to print a new line. - :type nl: bool or None - - :param lineno: The line that this node appears on in the source code. - :type lineno: int or None - - :param col_offset: The column that this node appears on in the - source code. - :type col_offset: int or None - - :param parent: The parent node in the syntax tree. - :type parent: NodeNG or None - """ - self.nl = nl - """Whether to print a new line. - - :type: bool or None - """ - - super().__init__(lineno, col_offset, parent) - - def postinit(self, dest=None, values=None): - """Do some setup after initialisation. - - :param dest: Where to print to. - :type dest: NodeNG or None - - :param values: What to print. - :type values: list(NodeNG) or None - """ - self.dest = dest - self.values = values - - -class Raise(Statement): - """Class representing an :class:`ast.Raise` node. - - >>> node = astroid.extract_node('raise RuntimeError("Something bad happened!")') - >>> node - - """ - - exc = None - """What is being raised. - - :type: NodeNG or None - """ - _astroid_fields = ("exc", "cause") - cause = None - """The exception being used to raise this one. - - :type: NodeNG or None - """ - - def postinit(self, exc=None, cause=None): - """Do some setup after initialisation. - - :param exc: What is being raised. - :type exc: NodeNG or None - - :param cause: The exception being used to raise this one. - :type cause: NodeNG or None - """ - self.exc = exc - self.cause = cause - - def raises_not_implemented(self): - """Check if this node raises a :class:`NotImplementedError`. - - :returns: True if this node raises a :class:`NotImplementedError`, - False otherwise. - :rtype: bool - """ - if not self.exc: - return False - for name in self.exc._get_name_nodes(): - if name.name == "NotImplementedError": - return True - return False - - def get_children(self): - if self.exc is not None: - yield self.exc - - if self.cause is not None: - yield self.cause - - -class Return(Statement): - """Class representing an :class:`ast.Return` node. - - >>> node = astroid.extract_node('return True') - >>> node - - """ - - _astroid_fields = ("value",) - value = None - """The value being returned. - - :type: NodeNG or None - """ - - def postinit(self, value=None): - """Do some setup after initialisation. - - :param value: The value being returned. - :type value: NodeNG or None - """ - self.value = value - - def get_children(self): - if self.value is not None: - yield self.value - - def is_tuple_return(self): - return isinstance(self.value, Tuple) - - def _get_return_nodes_skip_functions(self): - yield self - - -class Set(_BaseContainer): - """Class representing an :class:`ast.Set` node. - - >>> node = astroid.extract_node('{1, 2, 3}') - >>> node - - """ - - def pytype(self): - """Get the name of the type that this node represents. - - :returns: The name of the type. - :rtype: str - """ - return "%s.set" % BUILTINS - - -class Slice(NodeNG): - """Class representing an :class:`ast.Slice` node. - - >>> node = astroid.extract_node('things[1:3]') - >>> node - - >>> node.slice - - """ - - _astroid_fields = ("lower", "upper", "step") - lower = None - """The lower index in the slice. - - :type: NodeNG or None - """ - upper = None - """The upper index in the slice. - - :type: NodeNG or None - """ - step = None - """The step to take between indexes. - - :type: NodeNG or None - """ - - def postinit(self, lower=None, upper=None, step=None): - """Do some setup after initialisation. - - :param lower: The lower index in the slice. - :value lower: NodeNG or None - - :param upper: The upper index in the slice. - :value upper: NodeNG or None - - :param step: The step to take between index. - :param step: NodeNG or None - """ - self.lower = lower - self.upper = upper - self.step = step - - def _wrap_attribute(self, attr): - """Wrap the empty attributes of the Slice in a Const node.""" - if not attr: - const = const_factory(attr) - const.parent = self - return const - return attr - - @decorators.cachedproperty - def _proxied(self): - builtins = MANAGER.builtins_module - return builtins.getattr("slice")[0] - - def pytype(self): - """Get the name of the type that this node represents. - - :returns: The name of the type. - :rtype: str - """ - return "%s.slice" % BUILTINS - - def igetattr(self, attrname, context=None): - """Infer the possible values of the given attribute on the slice. - - :param attrname: The name of the attribute to infer. - :type attrname: str - - :returns: The inferred possible values. - :rtype: iterable(NodeNG) - """ - if attrname == "start": - yield self._wrap_attribute(self.lower) - elif attrname == "stop": - yield self._wrap_attribute(self.upper) - elif attrname == "step": - yield self._wrap_attribute(self.step) - else: - yield from self.getattr(attrname, context=context) - - def getattr(self, attrname, context=None): - return self._proxied.getattr(attrname, context) - - def get_children(self): - if self.lower is not None: - yield self.lower - - if self.upper is not None: - yield self.upper - - if self.step is not None: - yield self.step - - -class Starred(mixins.ParentAssignTypeMixin, NodeNG): - """Class representing an :class:`ast.Starred` node. - - >>> node = astroid.extract_node('*args') - >>> node - - """ - - _astroid_fields = ("value",) - _other_fields = ("ctx",) - value = None - """What is being unpacked. - - :type: NodeNG or None - """ - - def __init__(self, ctx=None, lineno=None, col_offset=None, parent=None): - """ - :param ctx: Whether the list is assigned to or loaded from. - :type ctx: Context or None - - :param lineno: The line that this node appears on in the source code. - :type lineno: int or None - - :param col_offset: The column that this node appears on in the - source code. - :type col_offset: int or None - - :param parent: The parent node in the syntax tree. - :type parent: NodeNG or None - """ - self.ctx = ctx - """Whether the starred item is assigned to or loaded from. - - :type: Context or None - """ - - super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) - - def postinit(self, value=None): - """Do some setup after initialisation. - - :param value: What is being unpacked. - :type value: NodeNG or None - """ - self.value = value - - def get_children(self): - yield self.value - - -class Subscript(NodeNG): - """Class representing an :class:`ast.Subscript` node. - - >>> node = astroid.extract_node('things[1:3]') - >>> node - - """ - - _astroid_fields = ("value", "slice") - _other_fields = ("ctx",) - value = None - """What is being indexed. - - :type: NodeNG or None - """ - slice = None - """The slice being used to lookup. - - :type: NodeNG or None - """ - - def __init__(self, ctx=None, lineno=None, col_offset=None, parent=None): - """ - :param ctx: Whether the subscripted item is assigned to or loaded from. - :type ctx: Context or None - - :param lineno: The line that this node appears on in the source code. - :type lineno: int or None - - :param col_offset: The column that this node appears on in the - source code. - :type col_offset: int or None - - :param parent: The parent node in the syntax tree. - :type parent: NodeNG or None - """ - self.ctx = ctx - """Whether the subscripted item is assigned to or loaded from. - - :type: Context or None - """ - - super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) - - # pylint: disable=redefined-builtin; had to use the same name as builtin ast module. - def postinit(self, value=None, slice=None): - """Do some setup after initialisation. - - :param value: What is being indexed. - :type value: NodeNG or None - - :param slice: The slice being used to lookup. - :type slice: NodeNG or None - """ - self.value = value - self.slice = slice - - def get_children(self): - yield self.value - yield self.slice - - -class TryExcept(mixins.MultiLineBlockMixin, mixins.BlockRangeMixIn, Statement): - """Class representing an :class:`ast.TryExcept` node. - - >>> node = astroid.extract_node(''' - try: - do_something() - except Exception as error: - print("Error!") - ''') - >>> node - - """ - - _astroid_fields = ("body", "handlers", "orelse") - _multi_line_block_fields = ("body", "handlers", "orelse") - body = None - """The contents of the block to catch exceptions from. - - :type: list(NodeNG) or None - """ - handlers = None - """The exception handlers. - - :type: list(ExceptHandler) or None - """ - orelse = None - """The contents of the ``else`` block. - - :type: list(NodeNG) or None - """ - - def postinit(self, body=None, handlers=None, orelse=None): - """Do some setup after initialisation. - - :param body: The contents of the block to catch exceptions from. - :type body: list(NodeNG) or None - - :param handlers: The exception handlers. - :type handlers: list(ExceptHandler) or None - - :param orelse: The contents of the ``else`` block. - :type orelse: list(NodeNG) or None - """ - self.body = body - self.handlers = handlers - self.orelse = orelse - - def _infer_name(self, frame, name): - return name - - def block_range(self, lineno): - """Get a range from the given line number to where this node ends. - - :param lineno: The line number to start the range at. - :type lineno: int - - :returns: The range of line numbers that this node belongs to, - starting at the given line number. - :rtype: tuple(int, int) - """ - last = None - for exhandler in self.handlers: - if exhandler.type and lineno == exhandler.type.fromlineno: - return lineno, lineno - if exhandler.body[0].fromlineno <= lineno <= exhandler.body[-1].tolineno: - return lineno, exhandler.body[-1].tolineno - if last is None: - last = exhandler.body[0].fromlineno - 1 - return self._elsed_block_range(lineno, self.orelse, last) - - def get_children(self): - yield from self.body - - yield from self.handlers or () - yield from self.orelse or () - - -class TryFinally(mixins.MultiLineBlockMixin, mixins.BlockRangeMixIn, Statement): - """Class representing an :class:`ast.TryFinally` node. - - >>> node = astroid.extract_node(''' - try: - do_something() - except Exception as error: - print("Error!") - finally: - print("Cleanup!") - ''') - >>> node - - """ - - _astroid_fields = ("body", "finalbody") - _multi_line_block_fields = ("body", "finalbody") - body = None - """The try-except that the finally is attached to. - - :type: list(TryExcept) or None - """ - finalbody = None - """The contents of the ``finally`` block. - - :type: list(NodeNG) or None - """ - - def postinit(self, body=None, finalbody=None): - """Do some setup after initialisation. - - :param body: The try-except that the finally is attached to. - :type body: list(TryExcept) or None - - :param finalbody: The contents of the ``finally`` block. - :type finalbody: list(NodeNG) or None - """ - self.body = body - self.finalbody = finalbody - - def block_range(self, lineno): - """Get a range from the given line number to where this node ends. - - :param lineno: The line number to start the range at. - :type lineno: int - - :returns: The range of line numbers that this node belongs to, - starting at the given line number. - :rtype: tuple(int, int) - """ - child = self.body[0] - # py2.5 try: except: finally: - if ( - isinstance(child, TryExcept) - and child.fromlineno == self.fromlineno - and child.tolineno >= lineno > self.fromlineno - ): - return child.block_range(lineno) - return self._elsed_block_range(lineno, self.finalbody) - - def get_children(self): - yield from self.body - yield from self.finalbody - - -class Tuple(_BaseContainer): - """Class representing an :class:`ast.Tuple` node. - - >>> node = astroid.extract_node('(1, 2, 3)') - >>> node - - """ - - _other_fields = ("ctx",) - - def __init__(self, ctx=None, lineno=None, col_offset=None, parent=None): - """ - :param ctx: Whether the tuple is assigned to or loaded from. - :type ctx: Context or None - - :param lineno: The line that this node appears on in the source code. - :type lineno: int or None - - :param col_offset: The column that this node appears on in the - source code. - :type col_offset: int or None - - :param parent: The parent node in the syntax tree. - :type parent: NodeNG or None - """ - self.ctx = ctx - """Whether the tuple is assigned to or loaded from. - - :type: Context or None - """ - - super().__init__(lineno, col_offset, parent) - - def pytype(self): - """Get the name of the type that this node represents. - - :returns: The name of the type. - :rtype: str - """ - return "%s.tuple" % BUILTINS - - def getitem(self, index, context=None): - """Get an item from this node. - - :param index: The node to use as a subscript index. - :type index: Const or Slice - """ - return _container_getitem(self, self.elts, index, context=context) - - -class UnaryOp(NodeNG): - """Class representing an :class:`ast.UnaryOp` node. - - >>> node = astroid.extract_node('-5') - >>> node - - """ - - _astroid_fields = ("operand",) - _other_fields = ("op",) - operand = None - """What the unary operator is applied to. - - :type: NodeNG or None - """ - - def __init__(self, op=None, lineno=None, col_offset=None, parent=None): - """ - :param op: The operator. - :type: str or None - - :param lineno: The line that this node appears on in the source code. - :type lineno: int or None - - :param col_offset: The column that this node appears on in the - source code. - :type col_offset: int or None - - :param parent: The parent node in the syntax tree. - :type parent: NodeNG or None - """ - self.op = op - """The operator. - - :type: str or None - """ - - super().__init__(lineno, col_offset, parent) - - def postinit(self, operand=None): - """Do some setup after initialisation. - - :param operand: What the unary operator is applied to. - :type operand: NodeNG or None - """ - self.operand = operand - - # This is set by inference.py - def _infer_unaryop(self, context=None): - raise NotImplementedError - - def type_errors(self, context=None): - """Get a list of type errors which can occur during inference. - - Each TypeError is represented by a :class:`BadBinaryOperationMessage`, - which holds the original exception. - - :returns: The list of possible type errors. - :rtype: list(BadBinaryOperationMessage) - """ - try: - results = self._infer_unaryop(context=context) - return [ - result - for result in results - if isinstance(result, util.BadUnaryOperationMessage) - ] - except exceptions.InferenceError: - return [] - - def get_children(self): - yield self.operand - - def op_precedence(self): - if self.op == "not": - return OP_PRECEDENCE[self.op] - - return super().op_precedence() - - -class While(mixins.MultiLineBlockMixin, mixins.BlockRangeMixIn, Statement): - """Class representing an :class:`ast.While` node. - - >>> node = astroid.extract_node(''' - while condition(): - print("True") - ''') - >>> node - - """ - - _astroid_fields = ("test", "body", "orelse") - _multi_line_block_fields = ("body", "orelse") - test = None - """The condition that the loop tests. - - :type: NodeNG or None - """ - body = None - """The contents of the loop. - - :type: list(NodeNG) or None - """ - orelse = None - """The contents of the ``else`` block. - - :type: list(NodeNG) or None - """ - - def postinit(self, test=None, body=None, orelse=None): - """Do some setup after initialisation. - - :param test: The condition that the loop tests. - :type test: NodeNG or None - - :param body: The contents of the loop. - :type body: list(NodeNG) or None - - :param orelse: The contents of the ``else`` block. - :type orelse: list(NodeNG) or None - """ - self.test = test - self.body = body - self.orelse = orelse - - @decorators.cachedproperty - def blockstart_tolineno(self): - """The line on which the beginning of this block ends. - - :type: int - """ - return self.test.tolineno - - def block_range(self, lineno): - """Get a range from the given line number to where this node ends. - - :param lineno: The line number to start the range at. - :type lineno: int - - :returns: The range of line numbers that this node belongs to, - starting at the given line number. - :rtype: tuple(int, int) - """ - return self._elsed_block_range(lineno, self.orelse) - - def get_children(self): - yield self.test - - yield from self.body - yield from self.orelse - - def _get_yield_nodes_skip_lambdas(self): - """A While node can contain a Yield node in the test""" - yield from self.test._get_yield_nodes_skip_lambdas() - yield from super()._get_yield_nodes_skip_lambdas() - - -class With( - mixins.MultiLineBlockMixin, - mixins.BlockRangeMixIn, - mixins.AssignTypeMixin, - Statement, -): - """Class representing an :class:`ast.With` node. - - >>> node = astroid.extract_node(''' - with open(file_path) as file_: - print(file_.read()) - ''') - >>> node - - """ - - _astroid_fields = ("items", "body") - _other_other_fields = ("type_annotation",) - _multi_line_block_fields = ("body",) - items = None - """The pairs of context managers and the names they are assigned to. - - :type: list(tuple(NodeNG, AssignName or None)) or None - """ - body = None - """The contents of the ``with`` block. - - :type: list(NodeNG) or None - """ - type_annotation = None - """If present, this will contain the type annotation passed by a type comment - - :type: NodeNG or None - """ - - def postinit(self, items=None, body=None, type_annotation=None): - """Do some setup after initialisation. - - :param items: The pairs of context managers and the names - they are assigned to. - :type items: list(tuple(NodeNG, AssignName or None)) or None - - :param body: The contents of the ``with`` block. - :type body: list(NodeNG) or None - """ - self.items = items - self.body = body - self.type_annotation = type_annotation - - @decorators.cachedproperty - def blockstart_tolineno(self): - """The line on which the beginning of this block ends. - - :type: int - """ - return self.items[-1][0].tolineno - - def get_children(self): - """Get the child nodes below this node. - - :returns: The children. - :rtype: iterable(NodeNG) - """ - for expr, var in self.items: - yield expr - if var: - yield var - yield from self.body - - -class AsyncWith(With): - """Asynchronous ``with`` built with the ``async`` keyword.""" - - -class Yield(NodeNG): - """Class representing an :class:`ast.Yield` node. - - >>> node = astroid.extract_node('yield True') - >>> node - - """ - - _astroid_fields = ("value",) - value = None - """The value to yield. - - :type: NodeNG or None - """ - - def postinit(self, value=None): - """Do some setup after initialisation. - - :param value: The value to yield. - :type value: NodeNG or None - """ - self.value = value - - def get_children(self): - if self.value is not None: - yield self.value - - def _get_yield_nodes_skip_lambdas(self): - yield self - - -class YieldFrom(Yield): - """Class representing an :class:`ast.YieldFrom` node.""" - - -class DictUnpack(mixins.NoChildrenMixin, NodeNG): - """Represents the unpacking of dicts into dicts using :pep:`448`.""" - - -class FormattedValue(NodeNG): - """Class representing an :class:`ast.FormattedValue` node. - - Represents a :pep:`498` format string. - - >>> node = astroid.extract_node('f"Format {type_}"') - >>> node - - >>> node.values - [, ] - """ - - _astroid_fields = ("value", "format_spec") - value = None - """The value to be formatted into the string. - - :type: NodeNG or None - """ - conversion = None - """The type of formatting to be applied to the value. - - .. seealso:: - :class:`ast.FormattedValue` - - :type: int or None - """ - format_spec = None - """The formatting to be applied to the value. - - .. seealso:: - :class:`ast.FormattedValue` - - :type: JoinedStr or None - """ - - def postinit(self, value, conversion=None, format_spec=None): - """Do some setup after initialisation. - - :param value: The value to be formatted into the string. - :type value: NodeNG - - :param conversion: The type of formatting to be applied to the value. - :type conversion: int or None - - :param format_spec: The formatting to be applied to the value. - :type format_spec: JoinedStr or None - """ - self.value = value - self.conversion = conversion - self.format_spec = format_spec - - def get_children(self): - yield self.value - - if self.format_spec is not None: - yield self.format_spec - - -class JoinedStr(NodeNG): - """Represents a list of string expressions to be joined. - - >>> node = astroid.extract_node('f"Format {type_}"') - >>> node - - """ - - _astroid_fields = ("values",) - values = None - """The string expressions to be joined. - - :type: list(FormattedValue or Const) or None - """ - - def postinit(self, values=None): - """Do some setup after initialisation. - - :param value: The string expressions to be joined. - - :type: list(FormattedValue or Const) or None - """ - self.values = values - - def get_children(self): - yield from self.values - - -class NamedExpr(mixins.AssignTypeMixin, NodeNG): - """Represents the assignment from the assignment expression - - >>> module = astroid.parse('if a := 1: pass') - >>> module.body[0].test - - """ - - _astroid_fields = ("target", "value") - target = None - """The assignment target - - :type: Name - """ - value = None - """The value that gets assigned in the expression - - :type: NodeNG - """ - - def postinit(self, target, value): - self.target = target - self.value = value - - -class Unknown(mixins.AssignTypeMixin, NodeNG): - """This node represents a node in a constructed AST where - introspection is not possible. At the moment, it's only used in - the args attribute of FunctionDef nodes where function signature - introspection failed. - """ - - name = "Unknown" - - def qname(self): - return "Unknown" - - def infer(self, context=None, **kwargs): - """Inference on an Unknown node immediately terminates.""" - yield util.Uninferable - - -class EvaluatedObject(NodeNG): - """Contains an object that has already been inferred - - This class is useful to pre-evaluate a particular node, - with the resulting class acting as the non-evaluated node. - """ - - name = "EvaluatedObject" - _astroid_fields = ("original",) - _other_fields = ("value",) - - original = None - """The original node that has already been evaluated - - :type: NodeNG - """ - - value = None - """The inferred value - - :type: Union[Uninferable, NodeNG] - """ - - def __init__(self, original, value): - self.original = original - self.value = value - super().__init__( - lineno=self.original.lineno, - col_offset=self.original.col_offset, - parent=self.original.parent, - ) - - def infer(self, context=None, **kwargs): - yield self.value - - -# constants ############################################################## - -CONST_CLS = { - list: List, - tuple: Tuple, - dict: Dict, - set: Set, - type(None): Const, - type(NotImplemented): Const, -} -if PY38: - CONST_CLS[type(...)] = Const - - -def _update_const_classes(): - """update constant classes, so the keys of CONST_CLS can be reused""" - klasses = (bool, int, float, complex, str, bytes) - for kls in klasses: - CONST_CLS[kls] = Const - - -_update_const_classes() - - -def _two_step_initialization(cls, value): - instance = cls() - instance.postinit(value) - return instance - - -def _dict_initialization(cls, value): - if isinstance(value, dict): - value = tuple(value.items()) - return _two_step_initialization(cls, value) - - -_CONST_CLS_CONSTRUCTORS = { - List: _two_step_initialization, - Tuple: _two_step_initialization, - Dict: _dict_initialization, - Set: _two_step_initialization, - Const: lambda cls, value: cls(value), -} - - -def const_factory(value): - """return an astroid node for a python value""" - # XXX we should probably be stricter here and only consider stuff in - # CONST_CLS or do better treatment: in case where value is not in CONST_CLS, - # we should rather recall the builder on this value than returning an empty - # node (another option being that const_factory shouldn't be called with something - # not in CONST_CLS) - assert not isinstance(value, NodeNG) - - # Hack for ignoring elements of a sequence - # or a mapping, in order to avoid transforming - # each element to an AST. This is fixed in 2.0 - # and this approach is a temporary hack. - if isinstance(value, (list, set, tuple, dict)): - elts = [] - else: - elts = value - - try: - initializer_cls = CONST_CLS[value.__class__] - initializer = _CONST_CLS_CONSTRUCTORS[initializer_cls] - return initializer(initializer_cls, elts) - except (KeyError, AttributeError): - node = EmptyNode() - node.object = value - return node - - -def is_from_decorator(node): - """Return True if the given node is the child of a decorator""" - parent = node.parent - while parent is not None: - if isinstance(parent, Decorators): - return True - parent = parent.parent - return False diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/nodes.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/nodes.py deleted file mode 100644 index 4ce4ebe..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/nodes.py +++ /dev/null @@ -1,176 +0,0 @@ -# Copyright (c) 2006-2011, 2013 LOGILAB S.A. (Paris, FRANCE) -# Copyright (c) 2010 Daniel Harding -# Copyright (c) 2014-2020 Claudiu Popa -# Copyright (c) 2014 Google, Inc. -# Copyright (c) 2015-2016 Ceridwen -# Copyright (c) 2016 Jared Garst -# Copyright (c) 2017 Ashley Whetter -# Copyright (c) 2017 rr- -# Copyright (c) 2018 Bryce Guinta - -# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html -# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER - -"""Every available node class. - -.. seealso:: - :doc:`ast documentation ` - -All nodes inherit from :class:`~astroid.node_classes.NodeNG`. -""" -# pylint: disable=unused-import,redefined-builtin - -from astroid.node_classes import ( - Arguments, - AssignAttr, - Assert, - Assign, - AnnAssign, - AssignName, - AugAssign, - Repr, - BinOp, - BoolOp, - Break, - Call, - Compare, - Comprehension, - Const, - Continue, - Decorators, - DelAttr, - DelName, - Delete, - Dict, - Expr, - Ellipsis, - EmptyNode, - ExceptHandler, - Exec, - ExtSlice, - For, - ImportFrom, - Attribute, - Global, - If, - IfExp, - Import, - Index, - Keyword, - List, - Name, - NamedExpr, - Nonlocal, - Pass, - Print, - Raise, - Return, - Set, - Slice, - Starred, - Subscript, - TryExcept, - TryFinally, - Tuple, - UnaryOp, - While, - With, - Yield, - YieldFrom, - const_factory, - AsyncFor, - Await, - AsyncWith, - FormattedValue, - JoinedStr, - # Node not present in the builtin ast module. - DictUnpack, - Unknown, - EvaluatedObject, -) -from astroid.scoped_nodes import ( - Module, - GeneratorExp, - Lambda, - DictComp, - ListComp, - SetComp, - FunctionDef, - ClassDef, - AsyncFunctionDef, -) - - -ALL_NODE_CLASSES = ( - AsyncFunctionDef, - AsyncFor, - AsyncWith, - Await, - Arguments, - AssignAttr, - Assert, - Assign, - AnnAssign, - AssignName, - AugAssign, - Repr, - BinOp, - BoolOp, - Break, - Call, - ClassDef, - Compare, - Comprehension, - Const, - Continue, - Decorators, - DelAttr, - DelName, - Delete, - Dict, - DictComp, - DictUnpack, - Expr, - Ellipsis, - EmptyNode, - ExceptHandler, - Exec, - ExtSlice, - For, - ImportFrom, - FunctionDef, - Attribute, - GeneratorExp, - Global, - If, - IfExp, - Import, - Index, - Keyword, - Lambda, - List, - ListComp, - Name, - NamedExpr, - Nonlocal, - Module, - Pass, - Print, - Raise, - Return, - Set, - SetComp, - Slice, - Starred, - Subscript, - TryExcept, - TryFinally, - Tuple, - UnaryOp, - While, - With, - Yield, - YieldFrom, - FormattedValue, - JoinedStr, -) diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/objects.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/objects.py deleted file mode 100644 index fb782e6..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/objects.py +++ /dev/null @@ -1,314 +0,0 @@ -# Copyright (c) 2015-2016, 2018-2020 Claudiu Popa -# Copyright (c) 2015-2016 Ceridwen -# Copyright (c) 2015 Florian Bruhin -# Copyright (c) 2016 Derek Gustafson -# Copyright (c) 2018 hippo91 -# Copyright (c) 2018 Bryce Guinta - -# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html -# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER - - -""" -Inference objects are a way to represent composite AST nodes, -which are used only as inference results, so they can't be found in the -original AST tree. For instance, inferring the following frozenset use, -leads to an inferred FrozenSet: - - Call(func=Name('frozenset'), args=Tuple(...)) -""" - -import builtins - -from astroid import bases -from astroid import decorators -from astroid import exceptions -from astroid import MANAGER -from astroid import node_classes -from astroid import scoped_nodes -from astroid import util - - -BUILTINS = builtins.__name__ -objectmodel = util.lazy_import("interpreter.objectmodel") - - -class FrozenSet(node_classes._BaseContainer): - """class representing a FrozenSet composite node""" - - def pytype(self): - return "%s.frozenset" % BUILTINS - - def _infer(self, context=None): - yield self - - @decorators.cachedproperty - def _proxied(self): # pylint: disable=method-hidden - ast_builtins = MANAGER.builtins_module - return ast_builtins.getattr("frozenset")[0] - - -class Super(node_classes.NodeNG): - """Proxy class over a super call. - - This class offers almost the same behaviour as Python's super, - which is MRO lookups for retrieving attributes from the parents. - - The *mro_pointer* is the place in the MRO from where we should - start looking, not counting it. *mro_type* is the object which - provides the MRO, it can be both a type or an instance. - *self_class* is the class where the super call is, while - *scope* is the function where the super call is. - """ - - # pylint: disable=unnecessary-lambda - special_attributes = util.lazy_descriptor(lambda: objectmodel.SuperModel()) - - # pylint: disable=super-init-not-called - def __init__(self, mro_pointer, mro_type, self_class, scope): - self.type = mro_type - self.mro_pointer = mro_pointer - self._class_based = False - self._self_class = self_class - self._scope = scope - - def _infer(self, context=None): - yield self - - def super_mro(self): - """Get the MRO which will be used to lookup attributes in this super.""" - if not isinstance(self.mro_pointer, scoped_nodes.ClassDef): - raise exceptions.SuperError( - "The first argument to super must be a subtype of " - "type, not {mro_pointer}.", - super_=self, - ) - - if isinstance(self.type, scoped_nodes.ClassDef): - # `super(type, type)`, most likely in a class method. - self._class_based = True - mro_type = self.type - else: - mro_type = getattr(self.type, "_proxied", None) - if not isinstance(mro_type, (bases.Instance, scoped_nodes.ClassDef)): - raise exceptions.SuperError( - "The second argument to super must be an " - "instance or subtype of type, not {type}.", - super_=self, - ) - - if not mro_type.newstyle: - raise exceptions.SuperError( - "Unable to call super on old-style classes.", super_=self - ) - - mro = mro_type.mro() - if self.mro_pointer not in mro: - raise exceptions.SuperError( - "The second argument to super must be an " - "instance or subtype of type, not {type}.", - super_=self, - ) - - index = mro.index(self.mro_pointer) - return mro[index + 1 :] - - @decorators.cachedproperty - def _proxied(self): - ast_builtins = MANAGER.builtins_module - return ast_builtins.getattr("super")[0] - - def pytype(self): - return "%s.super" % BUILTINS - - def display_type(self): - return "Super of" - - @property - def name(self): - """Get the name of the MRO pointer.""" - return self.mro_pointer.name - - def qname(self): - return "super" - - def igetattr(self, name, context=None): - """Retrieve the inferred values of the given attribute name.""" - - if name in self.special_attributes: - yield self.special_attributes.lookup(name) - return - - try: - mro = self.super_mro() - # Don't let invalid MROs or invalid super calls - # leak out as is from this function. - except exceptions.SuperError as exc: - raise exceptions.AttributeInferenceError( - ( - "Lookup for {name} on {target!r} because super call {super!r} " - "is invalid." - ), - target=self, - attribute=name, - context=context, - super_=exc.super_, - ) from exc - except exceptions.MroError as exc: - raise exceptions.AttributeInferenceError( - ( - "Lookup for {name} on {target!r} failed because {cls!r} has an " - "invalid MRO." - ), - target=self, - attribute=name, - context=context, - mros=exc.mros, - cls=exc.cls, - ) from exc - found = False - for cls in mro: - if name not in cls.locals: - continue - - found = True - for inferred in bases._infer_stmts([cls[name]], context, frame=self): - if not isinstance(inferred, scoped_nodes.FunctionDef): - yield inferred - continue - - # We can obtain different descriptors from a super depending - # on what we are accessing and where the super call is. - if inferred.type == "classmethod": - yield bases.BoundMethod(inferred, cls) - elif self._scope.type == "classmethod" and inferred.type == "method": - yield inferred - elif self._class_based or inferred.type == "staticmethod": - yield inferred - elif isinstance(inferred, Property): - function = inferred.function - try: - yield from function.infer_call_result( - caller=self, context=context - ) - except exceptions.InferenceError: - yield util.Uninferable - elif bases._is_property(inferred): - # TODO: support other descriptors as well. - try: - yield from inferred.infer_call_result(self, context) - except exceptions.InferenceError: - yield util.Uninferable - else: - yield bases.BoundMethod(inferred, cls) - - if not found: - raise exceptions.AttributeInferenceError( - target=self, attribute=name, context=context - ) - - def getattr(self, name, context=None): - return list(self.igetattr(name, context=context)) - - -class ExceptionInstance(bases.Instance): - """Class for instances of exceptions - - It has special treatment for some of the exceptions's attributes, - which are transformed at runtime into certain concrete objects, such as - the case of .args. - """ - - @decorators.cachedproperty - def special_attributes(self): - qname = self.qname() - instance = objectmodel.BUILTIN_EXCEPTIONS.get( - qname, objectmodel.ExceptionInstanceModel - ) - return instance()(self) - - -class DictInstance(bases.Instance): - """Special kind of instances for dictionaries - - This instance knows the underlying object model of the dictionaries, which means - that methods such as .values or .items can be properly inferred. - """ - - # pylint: disable=unnecessary-lambda - special_attributes = util.lazy_descriptor(lambda: objectmodel.DictModel()) - - -# Custom objects tailored for dictionaries, which are used to -# disambiguate between the types of Python 2 dict's method returns -# and Python 3 (where they return set like objects). -class DictItems(bases.Proxy): - __str__ = node_classes.NodeNG.__str__ - __repr__ = node_classes.NodeNG.__repr__ - - -class DictKeys(bases.Proxy): - __str__ = node_classes.NodeNG.__str__ - __repr__ = node_classes.NodeNG.__repr__ - - -class DictValues(bases.Proxy): - __str__ = node_classes.NodeNG.__str__ - __repr__ = node_classes.NodeNG.__repr__ - - -class PartialFunction(scoped_nodes.FunctionDef): - """A class representing partial function obtained via functools.partial""" - - def __init__( - self, call, name=None, doc=None, lineno=None, col_offset=None, parent=None - ): - super().__init__(name, doc, lineno, col_offset, parent) - self.filled_positionals = len(call.positional_arguments[1:]) - self.filled_args = call.positional_arguments[1:] - self.filled_keywords = call.keyword_arguments - - def infer_call_result(self, caller=None, context=None): - if context: - current_passed_keywords = { - keyword for (keyword, _) in context.callcontext.keywords - } - for keyword, value in self.filled_keywords.items(): - if keyword not in current_passed_keywords: - context.callcontext.keywords.append((keyword, value)) - - call_context_args = context.callcontext.args or [] - context.callcontext.args = self.filled_args + call_context_args - - return super().infer_call_result(caller=caller, context=context) - - def qname(self): - return self.__class__.__name__ - - -# TODO: Hack to solve the circular import problem between node_classes and objects -# This is not needed in 2.0, which has a cleaner design overall -node_classes.Dict.__bases__ = (node_classes.NodeNG, DictInstance) - - -class Property(scoped_nodes.FunctionDef): - """Class representing a Python property""" - - def __init__( - self, function, name=None, doc=None, lineno=None, col_offset=None, parent=None - ): - self.function = function - super().__init__(name, doc, lineno, col_offset, parent) - - # pylint: disable=unnecessary-lambda - special_attributes = util.lazy_descriptor(lambda: objectmodel.PropertyModel()) - type = "property" - - def pytype(self): - return "%s.property" % BUILTINS - - def infer_call_result(self, caller=None, context=None): - raise exceptions.InferenceError("Properties are not callable") - - def infer(self, context=None, **kwargs): - return iter((self,)) diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/protocols.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/protocols.py deleted file mode 100644 index 2cdf554..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/protocols.py +++ /dev/null @@ -1,780 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright (c) 2009-2011, 2013-2014 LOGILAB S.A. (Paris, FRANCE) -# Copyright (c) 2014-2020 Claudiu Popa -# Copyright (c) 2014 Google, Inc. -# Copyright (c) 2014 Eevee (Alex Munroe) -# Copyright (c) 2015-2016 Ceridwen -# Copyright (c) 2015 Dmitry Pribysh -# Copyright (c) 2016 Derek Gustafson -# Copyright (c) 2017-2018 Ashley Whetter -# Copyright (c) 2017 Łukasz Rogalski -# Copyright (c) 2017 rr- -# Copyright (c) 2018 Nick Drozd -# Copyright (c) 2018 Ville Skyttä -# Copyright (c) 2018 Bryce Guinta -# Copyright (c) 2018 HoverHell -# Copyright (c) 2019 Hugo van Kemenade - -# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html -# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER - -"""this module contains a set of functions to handle python protocols for nodes -where it makes sense. -""" - -import collections -import operator as operator_mod - -import itertools - -from astroid import Store -from astroid import arguments -from astroid import bases -from astroid import context as contextmod -from astroid import exceptions -from astroid import decorators -from astroid import node_classes -from astroid import helpers -from astroid import nodes -from astroid import util - -raw_building = util.lazy_import("raw_building") -objects = util.lazy_import("objects") - - -def _reflected_name(name): - return "__r" + name[2:] - - -def _augmented_name(name): - return "__i" + name[2:] - - -_CONTEXTLIB_MGR = "contextlib.contextmanager" -BIN_OP_METHOD = { - "+": "__add__", - "-": "__sub__", - "/": "__truediv__", - "//": "__floordiv__", - "*": "__mul__", - "**": "__pow__", - "%": "__mod__", - "&": "__and__", - "|": "__or__", - "^": "__xor__", - "<<": "__lshift__", - ">>": "__rshift__", - "@": "__matmul__", -} - -REFLECTED_BIN_OP_METHOD = { - key: _reflected_name(value) for (key, value) in BIN_OP_METHOD.items() -} -AUGMENTED_OP_METHOD = { - key + "=": _augmented_name(value) for (key, value) in BIN_OP_METHOD.items() -} - -UNARY_OP_METHOD = { - "+": "__pos__", - "-": "__neg__", - "~": "__invert__", - "not": None, # XXX not '__nonzero__' -} -_UNARY_OPERATORS = { - "+": operator_mod.pos, - "-": operator_mod.neg, - "~": operator_mod.invert, - "not": operator_mod.not_, -} - - -def _infer_unary_op(obj, op): - func = _UNARY_OPERATORS[op] - value = func(obj) - return nodes.const_factory(value) - - -nodes.Tuple.infer_unary_op = lambda self, op: _infer_unary_op(tuple(self.elts), op) -nodes.List.infer_unary_op = lambda self, op: _infer_unary_op(self.elts, op) -nodes.Set.infer_unary_op = lambda self, op: _infer_unary_op(set(self.elts), op) -nodes.Const.infer_unary_op = lambda self, op: _infer_unary_op(self.value, op) -nodes.Dict.infer_unary_op = lambda self, op: _infer_unary_op(dict(self.items), op) - -# Binary operations - -BIN_OP_IMPL = { - "+": lambda a, b: a + b, - "-": lambda a, b: a - b, - "/": lambda a, b: a / b, - "//": lambda a, b: a // b, - "*": lambda a, b: a * b, - "**": lambda a, b: a ** b, - "%": lambda a, b: a % b, - "&": lambda a, b: a & b, - "|": lambda a, b: a | b, - "^": lambda a, b: a ^ b, - "<<": lambda a, b: a << b, - ">>": lambda a, b: a >> b, - "@": operator_mod.matmul, -} -for _KEY, _IMPL in list(BIN_OP_IMPL.items()): - BIN_OP_IMPL[_KEY + "="] = _IMPL - - -@decorators.yes_if_nothing_inferred -def const_infer_binary_op(self, opnode, operator, other, context, _): - not_implemented = nodes.Const(NotImplemented) - if isinstance(other, nodes.Const): - try: - impl = BIN_OP_IMPL[operator] - try: - yield nodes.const_factory(impl(self.value, other.value)) - except TypeError: - # ArithmeticError is not enough: float >> float is a TypeError - yield not_implemented - except Exception: # pylint: disable=broad-except - yield util.Uninferable - except TypeError: - yield not_implemented - elif isinstance(self.value, str) and operator == "%": - # TODO(cpopa): implement string interpolation later on. - yield util.Uninferable - else: - yield not_implemented - - -nodes.Const.infer_binary_op = const_infer_binary_op - - -def _multiply_seq_by_int(self, opnode, other, context): - node = self.__class__(parent=opnode) - filtered_elts = ( - helpers.safe_infer(elt, context) or util.Uninferable - for elt in self.elts - if elt is not util.Uninferable - ) - node.elts = list(filtered_elts) * other.value - return node - - -def _filter_uninferable_nodes(elts, context): - for elt in elts: - if elt is util.Uninferable: - yield nodes.Unknown() - else: - for inferred in elt.infer(context): - if inferred is not util.Uninferable: - yield inferred - else: - yield nodes.Unknown() - - -@decorators.yes_if_nothing_inferred -def tl_infer_binary_op(self, opnode, operator, other, context, method): - not_implemented = nodes.Const(NotImplemented) - if isinstance(other, self.__class__) and operator == "+": - node = self.__class__(parent=opnode) - node.elts = list( - itertools.chain( - _filter_uninferable_nodes(self.elts, context), - _filter_uninferable_nodes(other.elts, context), - ) - ) - yield node - elif isinstance(other, nodes.Const) and operator == "*": - if not isinstance(other.value, int): - yield not_implemented - return - yield _multiply_seq_by_int(self, opnode, other, context) - elif isinstance(other, bases.Instance) and operator == "*": - # Verify if the instance supports __index__. - as_index = helpers.class_instance_as_index(other) - if not as_index: - yield util.Uninferable - else: - yield _multiply_seq_by_int(self, opnode, as_index, context) - else: - yield not_implemented - - -nodes.Tuple.infer_binary_op = tl_infer_binary_op -nodes.List.infer_binary_op = tl_infer_binary_op - - -@decorators.yes_if_nothing_inferred -def instance_class_infer_binary_op(self, opnode, operator, other, context, method): - return method.infer_call_result(self, context) - - -bases.Instance.infer_binary_op = instance_class_infer_binary_op -nodes.ClassDef.infer_binary_op = instance_class_infer_binary_op - - -# assignment ################################################################## - -"""the assigned_stmts method is responsible to return the assigned statement -(e.g. not inferred) according to the assignment type. - -The `assign_path` argument is used to record the lhs path of the original node. -For instance if we want assigned statements for 'c' in 'a, (b,c)', assign_path -will be [1, 1] once arrived to the Assign node. - -The `context` argument is the current inference context which should be given -to any intermediary inference necessary. -""" - - -def _resolve_looppart(parts, assign_path, context): - """recursive function to resolve multiple assignments on loops""" - assign_path = assign_path[:] - index = assign_path.pop(0) - for part in parts: - if part is util.Uninferable: - continue - if not hasattr(part, "itered"): - continue - try: - itered = part.itered() - except TypeError: - continue - for stmt in itered: - index_node = nodes.Const(index) - try: - assigned = stmt.getitem(index_node, context) - except ( - AttributeError, - exceptions.AstroidTypeError, - exceptions.AstroidIndexError, - ): - continue - if not assign_path: - # we achieved to resolved the assignment path, - # don't infer the last part - yield assigned - elif assigned is util.Uninferable: - break - else: - # we are not yet on the last part of the path - # search on each possibly inferred value - try: - yield from _resolve_looppart( - assigned.infer(context), assign_path, context - ) - except exceptions.InferenceError: - break - - -@decorators.raise_if_nothing_inferred -def for_assigned_stmts(self, node=None, context=None, assign_path=None): - if isinstance(self, nodes.AsyncFor) or getattr(self, "is_async", False): - # Skip inferring of async code for now - return dict(node=self, unknown=node, assign_path=assign_path, context=context) - if assign_path is None: - for lst in self.iter.infer(context): - if isinstance(lst, (nodes.Tuple, nodes.List)): - yield from lst.elts - else: - yield from _resolve_looppart(self.iter.infer(context), assign_path, context) - return dict(node=self, unknown=node, assign_path=assign_path, context=context) - - -nodes.For.assigned_stmts = for_assigned_stmts -nodes.Comprehension.assigned_stmts = for_assigned_stmts - - -def sequence_assigned_stmts(self, node=None, context=None, assign_path=None): - if assign_path is None: - assign_path = [] - try: - index = self.elts.index(node) - except ValueError as exc: - raise exceptions.InferenceError( - "Tried to retrieve a node {node!r} which does not exist", - node=self, - assign_path=assign_path, - context=context, - ) from exc - - assign_path.insert(0, index) - return self.parent.assigned_stmts( - node=self, context=context, assign_path=assign_path - ) - - -nodes.Tuple.assigned_stmts = sequence_assigned_stmts -nodes.List.assigned_stmts = sequence_assigned_stmts - - -def assend_assigned_stmts(self, node=None, context=None, assign_path=None): - return self.parent.assigned_stmts(node=self, context=context) - - -nodes.AssignName.assigned_stmts = assend_assigned_stmts -nodes.AssignAttr.assigned_stmts = assend_assigned_stmts - - -def _arguments_infer_argname(self, name, context): - # arguments information may be missing, in which case we can't do anything - # more - if not (self.arguments or self.vararg or self.kwarg): - yield util.Uninferable - return - - functype = self.parent.type - # first argument of instance/class method - if ( - self.arguments - and getattr(self.arguments[0], "name", None) == name - and functype != "staticmethod" - ): - cls = self.parent.parent.scope() - is_metaclass = isinstance(cls, nodes.ClassDef) and cls.type == "metaclass" - # If this is a metaclass, then the first argument will always - # be the class, not an instance. - if context.boundnode and isinstance(context.boundnode, bases.Instance): - cls = context.boundnode._proxied - if is_metaclass or functype == "classmethod": - yield cls - return - if functype == "method": - yield cls.instantiate_class() - return - - if context and context.callcontext: - call_site = arguments.CallSite(context.callcontext, context.extra_context) - yield from call_site.infer_argument(self.parent, name, context) - return - - if name == self.vararg: - vararg = nodes.const_factory(()) - vararg.parent = self - if not self.arguments and self.parent.name == "__init__": - cls = self.parent.parent.scope() - vararg.elts = [cls.instantiate_class()] - yield vararg - return - if name == self.kwarg: - kwarg = nodes.const_factory({}) - kwarg.parent = self - yield kwarg - return - # if there is a default value, yield it. And then yield Uninferable to reflect - # we can't guess given argument value - try: - context = contextmod.copy_context(context) - yield from self.default_value(name).infer(context) - yield util.Uninferable - except exceptions.NoDefault: - yield util.Uninferable - - -def arguments_assigned_stmts(self, node=None, context=None, assign_path=None): - if context.callcontext: - # reset call context/name - callcontext = context.callcontext - context = contextmod.copy_context(context) - context.callcontext = None - args = arguments.CallSite(callcontext, context=context) - return args.infer_argument(self.parent, node.name, context) - return _arguments_infer_argname(self, node.name, context) - - -nodes.Arguments.assigned_stmts = arguments_assigned_stmts - - -@decorators.raise_if_nothing_inferred -def assign_assigned_stmts(self, node=None, context=None, assign_path=None): - if not assign_path: - yield self.value - return None - yield from _resolve_assignment_parts( - self.value.infer(context), assign_path, context - ) - - return dict(node=self, unknown=node, assign_path=assign_path, context=context) - - -def assign_annassigned_stmts(self, node=None, context=None, assign_path=None): - for inferred in assign_assigned_stmts(self, node, context, assign_path): - if inferred is None: - yield util.Uninferable - else: - yield inferred - - -nodes.Assign.assigned_stmts = assign_assigned_stmts -nodes.AnnAssign.assigned_stmts = assign_annassigned_stmts -nodes.AugAssign.assigned_stmts = assign_assigned_stmts - - -def _resolve_assignment_parts(parts, assign_path, context): - """recursive function to resolve multiple assignments""" - assign_path = assign_path[:] - index = assign_path.pop(0) - for part in parts: - assigned = None - if isinstance(part, nodes.Dict): - # A dictionary in an iterating context - try: - assigned, _ = part.items[index] - except IndexError: - return - - elif hasattr(part, "getitem"): - index_node = nodes.Const(index) - try: - assigned = part.getitem(index_node, context) - except (exceptions.AstroidTypeError, exceptions.AstroidIndexError): - return - - if not assigned: - return - - if not assign_path: - # we achieved to resolved the assignment path, don't infer the - # last part - yield assigned - elif assigned is util.Uninferable: - return - else: - # we are not yet on the last part of the path search on each - # possibly inferred value - try: - yield from _resolve_assignment_parts( - assigned.infer(context), assign_path, context - ) - except exceptions.InferenceError: - return - - -@decorators.raise_if_nothing_inferred -def excepthandler_assigned_stmts(self, node=None, context=None, assign_path=None): - for assigned in node_classes.unpack_infer(self.type): - if isinstance(assigned, nodes.ClassDef): - assigned = objects.ExceptionInstance(assigned) - - yield assigned - return dict(node=self, unknown=node, assign_path=assign_path, context=context) - - -nodes.ExceptHandler.assigned_stmts = excepthandler_assigned_stmts - - -def _infer_context_manager(self, mgr, context): - inferred = next(mgr.infer(context=context)) - if isinstance(inferred, bases.Generator): - # Check if it is decorated with contextlib.contextmanager. - func = inferred.parent - if not func.decorators: - raise exceptions.InferenceError( - "No decorators found on inferred generator %s", node=func - ) - - for decorator_node in func.decorators.nodes: - decorator = next(decorator_node.infer(context=context)) - if isinstance(decorator, nodes.FunctionDef): - if decorator.qname() == _CONTEXTLIB_MGR: - break - else: - # It doesn't interest us. - raise exceptions.InferenceError(node=func) - - # Get the first yield point. If it has multiple yields, - # then a RuntimeError will be raised. - - possible_yield_points = func.nodes_of_class(nodes.Yield) - # Ignore yields in nested functions - yield_point = next( - (node for node in possible_yield_points if node.scope() == func), None - ) - if yield_point: - if not yield_point.value: - const = nodes.Const(None) - const.parent = yield_point - const.lineno = yield_point.lineno - yield const - else: - yield from yield_point.value.infer(context=context) - elif isinstance(inferred, bases.Instance): - try: - enter = next(inferred.igetattr("__enter__", context=context)) - except (exceptions.InferenceError, exceptions.AttributeInferenceError): - raise exceptions.InferenceError(node=inferred) - if not isinstance(enter, bases.BoundMethod): - raise exceptions.InferenceError(node=enter) - yield from enter.infer_call_result(self, context) - else: - raise exceptions.InferenceError(node=mgr) - - -@decorators.raise_if_nothing_inferred -def with_assigned_stmts(self, node=None, context=None, assign_path=None): - """Infer names and other nodes from a *with* statement. - - This enables only inference for name binding in a *with* statement. - For instance, in the following code, inferring `func` will return - the `ContextManager` class, not whatever ``__enter__`` returns. - We are doing this intentionally, because we consider that the context - manager result is whatever __enter__ returns and what it is binded - using the ``as`` keyword. - - class ContextManager(object): - def __enter__(self): - return 42 - with ContextManager() as f: - pass - - # ContextManager().infer() will return ContextManager - # f.infer() will return 42. - - Arguments: - self: nodes.With - node: The target of the assignment, `as (a, b)` in `with foo as (a, b)`. - context: Inference context used for caching already inferred objects - assign_path: - A list of indices, where each index specifies what item to fetch from - the inference results. - """ - try: - mgr = next(mgr for (mgr, vars) in self.items if vars == node) - except StopIteration: - return None - if assign_path is None: - yield from _infer_context_manager(self, mgr, context) - else: - for result in _infer_context_manager(self, mgr, context): - # Walk the assign_path and get the item at the final index. - obj = result - for index in assign_path: - if not hasattr(obj, "elts"): - raise exceptions.InferenceError( - "Wrong type ({targets!r}) for {node!r} assignment", - node=self, - targets=node, - assign_path=assign_path, - context=context, - ) - try: - obj = obj.elts[index] - except IndexError as exc: - raise exceptions.InferenceError( - "Tried to infer a nonexistent target with index {index} " - "in {node!r}.", - node=self, - targets=node, - assign_path=assign_path, - context=context, - ) from exc - except TypeError as exc: - raise exceptions.InferenceError( - "Tried to unpack a non-iterable value " "in {node!r}.", - node=self, - targets=node, - assign_path=assign_path, - context=context, - ) from exc - yield obj - return dict(node=self, unknown=node, assign_path=assign_path, context=context) - - -nodes.With.assigned_stmts = with_assigned_stmts - - -@decorators.raise_if_nothing_inferred -def named_expr_assigned_stmts(self, node, context=None, assign_path=None): - """Infer names and other nodes from an assignment expression""" - if self.target == node: - yield from self.value.infer(context=context) - else: - raise exceptions.InferenceError( - "Cannot infer NamedExpr node {node!r}", - node=self, - assign_path=assign_path, - context=context, - ) - - -nodes.NamedExpr.assigned_stmts = named_expr_assigned_stmts - - -@decorators.yes_if_nothing_inferred -def starred_assigned_stmts(self, node=None, context=None, assign_path=None): - """ - Arguments: - self: nodes.Starred - node: a node related to the current underlying Node. - context: Inference context used for caching already inferred objects - assign_path: - A list of indices, where each index specifies what item to fetch from - the inference results. - """ - # pylint: disable=too-many-locals,too-many-branches,too-many-statements - def _determine_starred_iteration_lookups(starred, target, lookups): - # Determine the lookups for the rhs of the iteration - itered = target.itered() - for index, element in enumerate(itered): - if ( - isinstance(element, nodes.Starred) - and element.value.name == starred.value.name - ): - lookups.append((index, len(itered))) - break - if isinstance(element, nodes.Tuple): - lookups.append((index, len(element.itered()))) - _determine_starred_iteration_lookups(starred, element, lookups) - - stmt = self.statement() - if not isinstance(stmt, (nodes.Assign, nodes.For)): - raise exceptions.InferenceError( - "Statement {stmt!r} enclosing {node!r} " "must be an Assign or For node.", - node=self, - stmt=stmt, - unknown=node, - context=context, - ) - - if context is None: - context = contextmod.InferenceContext() - - if isinstance(stmt, nodes.Assign): - value = stmt.value - lhs = stmt.targets[0] - - if sum(1 for _ in lhs.nodes_of_class(nodes.Starred)) > 1: - raise exceptions.InferenceError( - "Too many starred arguments in the " " assignment targets {lhs!r}.", - node=self, - targets=lhs, - unknown=node, - context=context, - ) - - try: - rhs = next(value.infer(context)) - except exceptions.InferenceError: - yield util.Uninferable - return - if rhs is util.Uninferable or not hasattr(rhs, "itered"): - yield util.Uninferable - return - - try: - elts = collections.deque(rhs.itered()) - except TypeError: - yield util.Uninferable - return - - # Unpack iteratively the values from the rhs of the assignment, - # until the find the starred node. What will remain will - # be the list of values which the Starred node will represent - # This is done in two steps, from left to right to remove - # anything before the starred node and from right to left - # to remove anything after the starred node. - - for index, left_node in enumerate(lhs.elts): - if not isinstance(left_node, nodes.Starred): - if not elts: - break - elts.popleft() - continue - lhs_elts = collections.deque(reversed(lhs.elts[index:])) - for right_node in lhs_elts: - if not isinstance(right_node, nodes.Starred): - if not elts: - break - elts.pop() - continue - - # We're done unpacking. - elts = list(elts) - packed = nodes.List( - ctx=Store, parent=self, lineno=lhs.lineno, col_offset=lhs.col_offset - ) - packed.postinit(elts=elts) - yield packed - break - - if isinstance(stmt, nodes.For): - try: - inferred_iterable = next(stmt.iter.infer(context=context)) - except exceptions.InferenceError: - yield util.Uninferable - return - if inferred_iterable is util.Uninferable or not hasattr( - inferred_iterable, "itered" - ): - yield util.Uninferable - return - try: - itered = inferred_iterable.itered() - except TypeError: - yield util.Uninferable - return - - target = stmt.target - - if not isinstance(target, nodes.Tuple): - raise exceptions.InferenceError( - "Could not make sense of this, the target must be a tuple", - context=context, - ) - - lookups = [] - _determine_starred_iteration_lookups(self, target, lookups) - if not lookups: - raise exceptions.InferenceError( - "Could not make sense of this, needs at least a lookup", context=context - ) - - # Make the last lookup a slice, since that what we want for a Starred node - last_element_index, last_element_length = lookups[-1] - is_starred_last = last_element_index == (last_element_length - 1) - - lookup_slice = slice( - last_element_index, - None if is_starred_last else (last_element_length - last_element_index), - ) - lookups[-1] = lookup_slice - - for element in itered: - - # We probably want to infer the potential values *for each* element in an - # iterable, but we can't infer a list of all values, when only a list of - # step values are expected: - # - # for a, *b in [...]: - # b - # - # *b* should now point to just the elements at that particular iteration step, - # which astroid can't know about. - - found_element = None - for lookup in lookups: - if not hasattr(element, "itered"): - break - if not isinstance(lookup, slice): - # Grab just the index, not the whole length - lookup = lookup[0] - try: - itered_inner_element = element.itered() - element = itered_inner_element[lookup] - except IndexError: - break - except TypeError: - # Most likely the itered() call failed, cannot make sense of this - yield util.Uninferable - return - else: - found_element = element - - unpacked = nodes.List( - ctx=Store, parent=self, lineno=self.lineno, col_offset=self.col_offset - ) - unpacked.postinit(elts=found_element or []) - yield unpacked - return - - yield util.Uninferable - - -nodes.Starred.assigned_stmts = starred_assigned_stmts diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/raw_building.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/raw_building.py deleted file mode 100644 index b261277..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/raw_building.py +++ /dev/null @@ -1,483 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright (c) 2006-2014 LOGILAB S.A. (Paris, FRANCE) -# Copyright (c) 2012 FELD Boris -# Copyright (c) 2014-2020 Claudiu Popa -# Copyright (c) 2014 Google, Inc. -# Copyright (c) 2015-2016 Ceridwen -# Copyright (c) 2015 Florian Bruhin -# Copyright (c) 2015 Ovidiu Sabou -# Copyright (c) 2016 Derek Gustafson -# Copyright (c) 2016 Jakub Wilk -# Copyright (c) 2018 Ville Skyttä -# Copyright (c) 2018 Nick Drozd -# Copyright (c) 2018 Bryce Guinta -# Copyright (c) 2020 Robin Jarry - -# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html -# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER - -"""this module contains a set of functions to create astroid trees from scratch -(build_* functions) or from living object (object_build_* functions) -""" - -import builtins -import inspect -import os -import sys -import types - -from astroid import bases -from astroid import manager -from astroid import node_classes -from astroid import nodes - - -MANAGER = manager.AstroidManager() -# the keys of CONST_CLS eg python builtin types - -_CONSTANTS = tuple(node_classes.CONST_CLS) -_BUILTINS = vars(builtins) -TYPE_NONE = type(None) -TYPE_NOTIMPLEMENTED = type(NotImplemented) -TYPE_ELLIPSIS = type(...) - - -def _io_discrepancy(member): - # _io module names itself `io`: http://bugs.python.org/issue18602 - member_self = getattr(member, "__self__", None) - return ( - member_self - and inspect.ismodule(member_self) - and member_self.__name__ == "_io" - and member.__module__ == "io" - ) - - -def _attach_local_node(parent, node, name): - node.name = name # needed by add_local_node - parent.add_local_node(node) - - -def _add_dunder_class(func, member): - """Add a __class__ member to the given func node, if we can determine it.""" - python_cls = member.__class__ - cls_name = getattr(python_cls, "__name__", None) - if not cls_name: - return - cls_bases = [ancestor.__name__ for ancestor in python_cls.__bases__] - ast_klass = build_class(cls_name, cls_bases, python_cls.__doc__) - func.instance_attrs["__class__"] = [ast_klass] - - -_marker = object() - - -def attach_dummy_node(node, name, runtime_object=_marker): - """create a dummy node and register it in the locals of the given - node with the specified name - """ - enode = nodes.EmptyNode() - enode.object = runtime_object - _attach_local_node(node, enode, name) - - -def _has_underlying_object(self): - return self.object is not None and self.object is not _marker - - -nodes.EmptyNode.has_underlying_object = _has_underlying_object - - -def attach_const_node(node, name, value): - """create a Const node and register it in the locals of the given - node with the specified name - """ - if name not in node.special_attributes: - _attach_local_node(node, nodes.const_factory(value), name) - - -def attach_import_node(node, modname, membername): - """create a ImportFrom node and register it in the locals of the given - node with the specified name - """ - from_node = nodes.ImportFrom(modname, [(membername, None)]) - _attach_local_node(node, from_node, membername) - - -def build_module(name, doc=None): - """create and initialize an astroid Module node""" - node = nodes.Module(name, doc, pure_python=False) - node.package = False - node.parent = None - return node - - -def build_class(name, basenames=(), doc=None): - """create and initialize an astroid ClassDef node""" - node = nodes.ClassDef(name, doc) - for base in basenames: - basenode = nodes.Name() - basenode.name = base - node.bases.append(basenode) - basenode.parent = node - return node - - -def build_function(name, args=None, posonlyargs=None, defaults=None, doc=None): - """create and initialize an astroid FunctionDef node""" - args, defaults, posonlyargs = args or [], defaults or [], posonlyargs or [] - # first argument is now a list of decorators - func = nodes.FunctionDef(name, doc) - func.args = argsnode = nodes.Arguments() - argsnode.args = [] - argsnode.posonlyargs = [] - for arg in args: - argsnode.args.append(nodes.Name()) - argsnode.args[-1].name = arg - argsnode.args[-1].parent = argsnode - for arg in posonlyargs: - argsnode.posonlyargs.append(nodes.Name()) - argsnode.posonlyargs[-1].name = arg - argsnode.posonlyargs[-1].parent = argsnode - argsnode.defaults = [] - for default in defaults: - argsnode.defaults.append(nodes.const_factory(default)) - argsnode.defaults[-1].parent = argsnode - argsnode.kwarg = None - argsnode.vararg = None - argsnode.parent = func - if args: - register_arguments(func) - return func - - -def build_from_import(fromname, names): - """create and initialize an astroid ImportFrom import statement""" - return nodes.ImportFrom(fromname, [(name, None) for name in names]) - - -def register_arguments(func, args=None): - """add given arguments to local - - args is a list that may contains nested lists - (i.e. def func(a, (b, c, d)): ...) - """ - if args is None: - args = func.args.args - if func.args.vararg: - func.set_local(func.args.vararg, func.args) - if func.args.kwarg: - func.set_local(func.args.kwarg, func.args) - for arg in args: - if isinstance(arg, nodes.Name): - func.set_local(arg.name, arg) - else: - register_arguments(func, arg.elts) - - -def object_build_class(node, member, localname): - """create astroid for a living class object""" - basenames = [base.__name__ for base in member.__bases__] - return _base_class_object_build(node, member, basenames, localname=localname) - - -def object_build_function(node, member, localname): - """create astroid for a living function object""" - signature = inspect.signature(member) - args = [] - defaults = [] - posonlyargs = [] - for param_name, param in signature.parameters.items(): - if param.kind == inspect.Parameter.POSITIONAL_ONLY: - posonlyargs.append(param_name) - elif param.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD: - args.append(param_name) - elif param.kind == inspect.Parameter.VAR_POSITIONAL: - args.append(param_name) - elif param.kind == inspect.Parameter.VAR_KEYWORD: - args.append(param_name) - if param.default is not inspect._empty: - defaults.append(param.default) - func = build_function( - getattr(member, "__name__", None) or localname, - args, - posonlyargs, - defaults, - member.__doc__, - ) - node.add_local_node(func, localname) - - -def object_build_datadescriptor(node, member, name): - """create astroid for a living data descriptor object""" - return _base_class_object_build(node, member, [], name) - - -def object_build_methoddescriptor(node, member, localname): - """create astroid for a living method descriptor object""" - # FIXME get arguments ? - func = build_function( - getattr(member, "__name__", None) or localname, doc=member.__doc__ - ) - # set node's arguments to None to notice that we have no information, not - # and empty argument list - func.args.args = None - node.add_local_node(func, localname) - _add_dunder_class(func, member) - - -def _base_class_object_build(node, member, basenames, name=None, localname=None): - """create astroid for a living class object, with a given set of base names - (e.g. ancestors) - """ - klass = build_class( - name or getattr(member, "__name__", None) or localname, - basenames, - member.__doc__, - ) - klass._newstyle = isinstance(member, type) - node.add_local_node(klass, localname) - try: - # limit the instantiation trick since it's too dangerous - # (such as infinite test execution...) - # this at least resolves common case such as Exception.args, - # OSError.errno - if issubclass(member, Exception): - instdict = member().__dict__ - else: - raise TypeError - except TypeError: - pass - else: - for item_name, obj in instdict.items(): - valnode = nodes.EmptyNode() - valnode.object = obj - valnode.parent = klass - valnode.lineno = 1 - klass.instance_attrs[item_name] = [valnode] - return klass - - -def _build_from_function(node, name, member, module): - # verify this is not an imported function - try: - code = member.__code__ - except AttributeError: - # Some implementations don't provide the code object, - # such as Jython. - code = None - filename = getattr(code, "co_filename", None) - if filename is None: - assert isinstance(member, object) - object_build_methoddescriptor(node, member, name) - elif filename != getattr(module, "__file__", None): - attach_dummy_node(node, name, member) - else: - object_build_function(node, member, name) - - -def _safe_has_attribute(obj, member): - try: - return hasattr(obj, member) - except Exception: # pylint: disable=broad-except - return False - - -class InspectBuilder: - """class for building nodes from living object - - this is actually a really minimal representation, including only Module, - FunctionDef and ClassDef nodes and some others as guessed. - """ - - def __init__(self): - self._done = {} - self._module = None - - def inspect_build(self, module, modname=None, path=None): - """build astroid from a living module (i.e. using inspect) - this is used when there is no python source code available (either - because it's a built-in module or because the .py is not available) - """ - self._module = module - if modname is None: - modname = module.__name__ - try: - node = build_module(modname, module.__doc__) - except AttributeError: - # in jython, java modules have no __doc__ (see #109562) - node = build_module(modname) - node.file = node.path = os.path.abspath(path) if path else path - node.name = modname - MANAGER.cache_module(node) - node.package = hasattr(module, "__path__") - self._done = {} - self.object_build(node, module) - return node - - def object_build(self, node, obj): - """recursive method which create a partial ast from real objects - (only function, class, and method are handled) - """ - if obj in self._done: - return self._done[obj] - self._done[obj] = node - for name in dir(obj): - try: - member = getattr(obj, name) - except AttributeError: - # damned ExtensionClass.Base, I know you're there ! - attach_dummy_node(node, name) - continue - if inspect.ismethod(member): - member = member.__func__ - if inspect.isfunction(member): - _build_from_function(node, name, member, self._module) - elif inspect.isbuiltin(member): - if not _io_discrepancy(member) and self.imported_member( - node, member, name - ): - continue - object_build_methoddescriptor(node, member, name) - elif inspect.isclass(member): - if self.imported_member(node, member, name): - continue - if member in self._done: - class_node = self._done[member] - if class_node not in node.locals.get(name, ()): - node.add_local_node(class_node, name) - else: - class_node = object_build_class(node, member, name) - # recursion - self.object_build(class_node, member) - if name == "__class__" and class_node.parent is None: - class_node.parent = self._done[self._module] - elif inspect.ismethoddescriptor(member): - assert isinstance(member, object) - object_build_methoddescriptor(node, member, name) - elif inspect.isdatadescriptor(member): - assert isinstance(member, object) - object_build_datadescriptor(node, member, name) - elif isinstance(member, _CONSTANTS): - attach_const_node(node, name, member) - elif inspect.isroutine(member): - # This should be called for Jython, where some builtin - # methods aren't caught by isbuiltin branch. - _build_from_function(node, name, member, self._module) - elif _safe_has_attribute(member, "__all__"): - module = build_module(name) - _attach_local_node(node, module, name) - # recursion - self.object_build(module, member) - else: - # create an empty node so that the name is actually defined - attach_dummy_node(node, name, member) - return None - - def imported_member(self, node, member, name): - """verify this is not an imported class or handle it""" - # /!\ some classes like ExtensionClass doesn't have a __module__ - # attribute ! Also, this may trigger an exception on badly built module - # (see http://www.logilab.org/ticket/57299 for instance) - try: - modname = getattr(member, "__module__", None) - except TypeError: - modname = None - if modname is None: - if name in ("__new__", "__subclasshook__"): - # Python 2.5.1 (r251:54863, Sep 1 2010, 22:03:14) - # >>> print object.__new__.__module__ - # None - modname = builtins.__name__ - else: - attach_dummy_node(node, name, member) - return True - - real_name = {"gtk": "gtk_gtk", "_io": "io"}.get(modname, modname) - - if real_name != self._module.__name__: - # check if it sounds valid and then add an import node, else use a - # dummy node - try: - getattr(sys.modules[modname], name) - except (KeyError, AttributeError): - attach_dummy_node(node, name, member) - else: - attach_import_node(node, modname, name) - return True - return False - - -### astroid bootstrapping ###################################################### - -_CONST_PROXY = {} - -# TODO : find a nicer way to handle this situation; -def _set_proxied(const): - return _CONST_PROXY[const.value.__class__] - - -def _astroid_bootstrapping(): - """astroid bootstrapping the builtins module""" - # this boot strapping is necessary since we need the Const nodes to - # inspect_build builtins, and then we can proxy Const - builder = InspectBuilder() - astroid_builtin = builder.inspect_build(builtins) - - # pylint: disable=redefined-outer-name - for cls, node_cls in node_classes.CONST_CLS.items(): - if cls is TYPE_NONE: - proxy = build_class("NoneType") - proxy.parent = astroid_builtin - elif cls is TYPE_NOTIMPLEMENTED: - proxy = build_class("NotImplementedType") - proxy.parent = astroid_builtin - elif cls is TYPE_ELLIPSIS: - proxy = build_class("Ellipsis") - proxy.parent = astroid_builtin - else: - proxy = astroid_builtin.getattr(cls.__name__)[0] - if cls in (dict, list, set, tuple): - node_cls._proxied = proxy - else: - _CONST_PROXY[cls] = proxy - - # Set the builtin module as parent for some builtins. - nodes.Const._proxied = property(_set_proxied) - - _GeneratorType = nodes.ClassDef( - types.GeneratorType.__name__, types.GeneratorType.__doc__ - ) - _GeneratorType.parent = astroid_builtin - bases.Generator._proxied = _GeneratorType - builder.object_build(bases.Generator._proxied, types.GeneratorType) - - if hasattr(types, "AsyncGeneratorType"): - # pylint: disable=no-member; AsyncGeneratorType - _AsyncGeneratorType = nodes.ClassDef( - types.AsyncGeneratorType.__name__, types.AsyncGeneratorType.__doc__ - ) - _AsyncGeneratorType.parent = astroid_builtin - bases.AsyncGenerator._proxied = _AsyncGeneratorType - builder.object_build(bases.AsyncGenerator._proxied, types.AsyncGeneratorType) - builtin_types = ( - types.GetSetDescriptorType, - types.GeneratorType, - types.MemberDescriptorType, - TYPE_NONE, - TYPE_NOTIMPLEMENTED, - types.FunctionType, - types.MethodType, - types.BuiltinFunctionType, - types.ModuleType, - types.TracebackType, - ) - for _type in builtin_types: - if _type.__name__ not in astroid_builtin: - cls = nodes.ClassDef(_type.__name__, _type.__doc__) - cls.parent = astroid_builtin - builder.object_build(cls, _type) - astroid_builtin[_type.__name__] = cls - - -_astroid_bootstrapping() diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/rebuilder.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/rebuilder.py deleted file mode 100644 index 3fc1a83..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/rebuilder.py +++ /dev/null @@ -1,1010 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright (c) 2009-2014 LOGILAB S.A. (Paris, FRANCE) -# Copyright (c) 2013-2020 Claudiu Popa -# Copyright (c) 2013-2014 Google, Inc. -# Copyright (c) 2014 Alexander Presnyakov -# Copyright (c) 2014 Eevee (Alex Munroe) -# Copyright (c) 2015-2016 Ceridwen -# Copyright (c) 2016-2017 Derek Gustafson -# Copyright (c) 2016 Jared Garst -# Copyright (c) 2017 Hugo -# Copyright (c) 2017 Łukasz Rogalski -# Copyright (c) 2017 rr- -# Copyright (c) 2018-2019 Ville Skyttä -# Copyright (c) 2018 Tomas Gavenciak -# Copyright (c) 2018 Serhiy Storchaka -# Copyright (c) 2018 Nick Drozd -# Copyright (c) 2018 Bryce Guinta -# Copyright (c) 2019-2020 Ashley Whetter -# Copyright (c) 2019 Hugo van Kemenade -# Copyright (c) 2019 Zbigniew Jędrzejewski-Szmek - -# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html -# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER - -"""this module contains utilities for rebuilding an _ast tree in -order to get a single Astroid representation -""" - -import sys -from typing import Optional - -import astroid -from astroid._ast import parse_function_type_comment, get_parser_module, ParserModule -from astroid import nodes - - -CONST_NAME_TRANSFORMS = {"None": None, "True": True, "False": False} - -REDIRECT = { - "arguments": "Arguments", - "comprehension": "Comprehension", - "ListCompFor": "Comprehension", - "GenExprFor": "Comprehension", - "excepthandler": "ExceptHandler", - "keyword": "Keyword", -} -PY37 = sys.version_info >= (3, 7) -PY38 = sys.version_info >= (3, 8) - - -def _visit_or_none(node, attr, visitor, parent, visit="visit", **kws): - """If the given node has an attribute, visits the attribute, and - otherwise returns None. - - """ - value = getattr(node, attr, None) - if value: - return getattr(visitor, visit)(value, parent, **kws) - - return None - - -class TreeRebuilder: - """Rebuilds the _ast tree to become an Astroid tree""" - - def __init__(self, manager, parser_module: Optional[ParserModule] = None): - self._manager = manager - self._global_names = [] - self._import_from_nodes = [] - self._delayed_assattr = [] - self._visit_meths = {} - - if parser_module is None: - self._parser_module = get_parser_module() - else: - self._parser_module = parser_module - self._module = self._parser_module.module - - def _get_doc(self, node): - try: - if PY37 and hasattr(node, "docstring"): - doc = node.docstring - return node, doc - if node.body and isinstance(node.body[0], self._module.Expr): - - first_value = node.body[0].value - if isinstance(first_value, self._module.Str) or ( - PY38 - and isinstance(first_value, self._module.Constant) - and isinstance(first_value.value, str) - ): - doc = first_value.value if PY38 else first_value.s - node.body = node.body[1:] - return node, doc - except IndexError: - pass # ast built from scratch - return node, None - - def _get_context(self, node): - return self._parser_module.context_classes.get(type(node.ctx), astroid.Load) - - def visit_module(self, node, modname, modpath, package): - """visit a Module node by returning a fresh instance of it""" - node, doc = self._get_doc(node) - newnode = nodes.Module( - name=modname, - doc=doc, - file=modpath, - path=[modpath], - package=package, - parent=None, - ) - newnode.postinit([self.visit(child, newnode) for child in node.body]) - return newnode - - def visit(self, node, parent): - cls = node.__class__ - if cls in self._visit_meths: - visit_method = self._visit_meths[cls] - else: - cls_name = cls.__name__ - visit_name = "visit_" + REDIRECT.get(cls_name, cls_name).lower() - visit_method = getattr(self, visit_name) - self._visit_meths[cls] = visit_method - return visit_method(node, parent) - - def _save_assignment(self, node, name=None): - """save assignement situation since node.parent is not available yet""" - if self._global_names and node.name in self._global_names[-1]: - node.root().set_local(node.name, node) - else: - node.parent.set_local(node.name, node) - - def visit_arg(self, node, parent): - """visit an arg node by returning a fresh AssName instance""" - return self.visit_assignname(node, parent, node.arg) - - def visit_arguments(self, node, parent): - """visit an Arguments node by returning a fresh instance of it""" - vararg, kwarg = node.vararg, node.kwarg - newnode = nodes.Arguments( - vararg.arg if vararg else None, kwarg.arg if kwarg else None, parent - ) - args = [self.visit(child, newnode) for child in node.args] - defaults = [self.visit(child, newnode) for child in node.defaults] - varargannotation = None - kwargannotation = None - posonlyargs = [] - # change added in 82732 (7c5c678e4164), vararg and kwarg - # are instances of `_ast.arg`, not strings - if vararg: - if node.vararg.annotation: - varargannotation = self.visit(node.vararg.annotation, newnode) - vararg = vararg.arg - if kwarg: - if node.kwarg.annotation: - kwargannotation = self.visit(node.kwarg.annotation, newnode) - kwarg = kwarg.arg - kwonlyargs = [self.visit(child, newnode) for child in node.kwonlyargs] - kw_defaults = [ - self.visit(child, newnode) if child else None for child in node.kw_defaults - ] - annotations = [ - self.visit(arg.annotation, newnode) if arg.annotation else None - for arg in node.args - ] - kwonlyargs_annotations = [ - self.visit(arg.annotation, newnode) if arg.annotation else None - for arg in node.kwonlyargs - ] - - posonlyargs_annotations = [] - if PY38: - posonlyargs = [self.visit(child, newnode) for child in node.posonlyargs] - posonlyargs_annotations = [ - self.visit(arg.annotation, newnode) if arg.annotation else None - for arg in node.posonlyargs - ] - type_comment_args = [ - self.check_type_comment(child, parent=newnode) for child in node.args - ] - type_comment_kwonlyargs = [ - self.check_type_comment(child, parent=newnode) for child in node.kwonlyargs - ] - type_comment_posonlyargs = [] - if PY38: - type_comment_posonlyargs = [ - self.check_type_comment(child, parent=newnode) - for child in node.posonlyargs - ] - - newnode.postinit( - args=args, - defaults=defaults, - kwonlyargs=kwonlyargs, - posonlyargs=posonlyargs, - kw_defaults=kw_defaults, - annotations=annotations, - kwonlyargs_annotations=kwonlyargs_annotations, - posonlyargs_annotations=posonlyargs_annotations, - varargannotation=varargannotation, - kwargannotation=kwargannotation, - type_comment_args=type_comment_args, - type_comment_kwonlyargs=type_comment_kwonlyargs, - type_comment_posonlyargs=type_comment_posonlyargs, - ) - # save argument names in locals: - if vararg: - newnode.parent.set_local(vararg, newnode) - if kwarg: - newnode.parent.set_local(kwarg, newnode) - return newnode - - def visit_assert(self, node, parent): - """visit a Assert node by returning a fresh instance of it""" - newnode = nodes.Assert(node.lineno, node.col_offset, parent) - if node.msg: - msg = self.visit(node.msg, newnode) - else: - msg = None - newnode.postinit(self.visit(node.test, newnode), msg) - return newnode - - def check_type_comment(self, node, parent): - type_comment = getattr(node, "type_comment", None) - if not type_comment: - return None - - try: - type_comment_ast = self._parser_module.parse(type_comment) - except SyntaxError: - # Invalid type comment, just skip it. - return None - - type_object = self.visit(type_comment_ast.body[0], parent=parent) - if not isinstance(type_object, nodes.Expr): - return None - - return type_object.value - - def check_function_type_comment(self, node): - type_comment = getattr(node, "type_comment", None) - if not type_comment: - return None - - try: - type_comment_ast = parse_function_type_comment(type_comment) - except SyntaxError: - # Invalid type comment, just skip it. - return None - - returns = None - argtypes = [ - self.visit(elem, node) for elem in (type_comment_ast.argtypes or []) - ] - if type_comment_ast.returns: - returns = self.visit(type_comment_ast.returns, node) - - return returns, argtypes - - # Async structs added in Python 3.5 - def visit_asyncfunctiondef(self, node, parent): - return self._visit_functiondef(nodes.AsyncFunctionDef, node, parent) - - def visit_asyncfor(self, node, parent): - return self._visit_for(nodes.AsyncFor, node, parent) - - def visit_await(self, node, parent): - newnode = nodes.Await(node.lineno, node.col_offset, parent) - newnode.postinit(value=self.visit(node.value, newnode)) - return newnode - - def visit_asyncwith(self, node, parent): - return self._visit_with(nodes.AsyncWith, node, parent) - - def visit_assign(self, node, parent): - """visit a Assign node by returning a fresh instance of it""" - newnode = nodes.Assign(node.lineno, node.col_offset, parent) - type_annotation = self.check_type_comment(node, parent=newnode) - newnode.postinit( - targets=[self.visit(child, newnode) for child in node.targets], - value=self.visit(node.value, newnode), - type_annotation=type_annotation, - ) - return newnode - - def visit_annassign(self, node, parent): - """visit an AnnAssign node by returning a fresh instance of it""" - newnode = nodes.AnnAssign(node.lineno, node.col_offset, parent) - annotation = _visit_or_none(node, "annotation", self, newnode) - newnode.postinit( - target=self.visit(node.target, newnode), - annotation=annotation, - simple=node.simple, - value=_visit_or_none(node, "value", self, newnode), - ) - return newnode - - def visit_assignname(self, node, parent, node_name=None): - """visit a node and return a AssignName node""" - newnode = nodes.AssignName( - node_name, - getattr(node, "lineno", None), - getattr(node, "col_offset", None), - parent, - ) - self._save_assignment(newnode) - return newnode - - def visit_augassign(self, node, parent): - """visit a AugAssign node by returning a fresh instance of it""" - newnode = nodes.AugAssign( - self._parser_module.bin_op_classes[type(node.op)] + "=", - node.lineno, - node.col_offset, - parent, - ) - newnode.postinit( - self.visit(node.target, newnode), self.visit(node.value, newnode) - ) - return newnode - - def visit_repr(self, node, parent): - """visit a Backquote node by returning a fresh instance of it""" - newnode = nodes.Repr(node.lineno, node.col_offset, parent) - newnode.postinit(self.visit(node.value, newnode)) - return newnode - - def visit_binop(self, node, parent): - """visit a BinOp node by returning a fresh instance of it""" - newnode = nodes.BinOp( - self._parser_module.bin_op_classes[type(node.op)], - node.lineno, - node.col_offset, - parent, - ) - newnode.postinit( - self.visit(node.left, newnode), self.visit(node.right, newnode) - ) - return newnode - - def visit_boolop(self, node, parent): - """visit a BoolOp node by returning a fresh instance of it""" - newnode = nodes.BoolOp( - self._parser_module.bool_op_classes[type(node.op)], - node.lineno, - node.col_offset, - parent, - ) - newnode.postinit([self.visit(child, newnode) for child in node.values]) - return newnode - - def visit_break(self, node, parent): - """visit a Break node by returning a fresh instance of it""" - return nodes.Break( - getattr(node, "lineno", None), getattr(node, "col_offset", None), parent - ) - - def visit_call(self, node, parent): - """visit a CallFunc node by returning a fresh instance of it""" - newnode = nodes.Call(node.lineno, node.col_offset, parent) - starargs = _visit_or_none(node, "starargs", self, newnode) - kwargs = _visit_or_none(node, "kwargs", self, newnode) - args = [self.visit(child, newnode) for child in node.args] - - if node.keywords: - keywords = [self.visit(child, newnode) for child in node.keywords] - else: - keywords = None - if starargs: - new_starargs = nodes.Starred( - col_offset=starargs.col_offset, - lineno=starargs.lineno, - parent=starargs.parent, - ) - new_starargs.postinit(value=starargs) - args.append(new_starargs) - if kwargs: - new_kwargs = nodes.Keyword( - arg=None, - col_offset=kwargs.col_offset, - lineno=kwargs.lineno, - parent=kwargs.parent, - ) - new_kwargs.postinit(value=kwargs) - if keywords: - keywords.append(new_kwargs) - else: - keywords = [new_kwargs] - - newnode.postinit(self.visit(node.func, newnode), args, keywords) - return newnode - - def visit_classdef(self, node, parent, newstyle=True): - """visit a ClassDef node to become astroid""" - node, doc = self._get_doc(node) - newnode = nodes.ClassDef(node.name, doc, node.lineno, node.col_offset, parent) - metaclass = None - for keyword in node.keywords: - if keyword.arg == "metaclass": - metaclass = self.visit(keyword, newnode).value - break - if node.decorator_list: - decorators = self.visit_decorators(node, newnode) - else: - decorators = None - newnode.postinit( - [self.visit(child, newnode) for child in node.bases], - [self.visit(child, newnode) for child in node.body], - decorators, - newstyle, - metaclass, - [ - self.visit(kwd, newnode) - for kwd in node.keywords - if kwd.arg != "metaclass" - ], - ) - return newnode - - def visit_const(self, node, parent): - """visit a Const node by returning a fresh instance of it""" - return nodes.Const( - node.value, - getattr(node, "lineno", None), - getattr(node, "col_offset", None), - parent, - ) - - def visit_continue(self, node, parent): - """visit a Continue node by returning a fresh instance of it""" - return nodes.Continue( - getattr(node, "lineno", None), getattr(node, "col_offset", None), parent - ) - - def visit_compare(self, node, parent): - """visit a Compare node by returning a fresh instance of it""" - newnode = nodes.Compare(node.lineno, node.col_offset, parent) - newnode.postinit( - self.visit(node.left, newnode), - [ - ( - self._parser_module.cmp_op_classes[op.__class__], - self.visit(expr, newnode), - ) - for (op, expr) in zip(node.ops, node.comparators) - ], - ) - return newnode - - def visit_comprehension(self, node, parent): - """visit a Comprehension node by returning a fresh instance of it""" - newnode = nodes.Comprehension(parent) - newnode.postinit( - self.visit(node.target, newnode), - self.visit(node.iter, newnode), - [self.visit(child, newnode) for child in node.ifs], - getattr(node, "is_async", None), - ) - return newnode - - def visit_decorators(self, node, parent): - """visit a Decorators node by returning a fresh instance of it""" - # /!\ node is actually an _ast.FunctionDef node while - # parent is an astroid.nodes.FunctionDef node - if PY38: - # Set the line number of the first decorator for Python 3.8+. - lineno = node.decorator_list[0].lineno - else: - lineno = node.lineno - newnode = nodes.Decorators(lineno, node.col_offset, parent) - newnode.postinit([self.visit(child, newnode) for child in node.decorator_list]) - return newnode - - def visit_delete(self, node, parent): - """visit a Delete node by returning a fresh instance of it""" - newnode = nodes.Delete(node.lineno, node.col_offset, parent) - newnode.postinit([self.visit(child, newnode) for child in node.targets]) - return newnode - - def _visit_dict_items(self, node, parent, newnode): - for key, value in zip(node.keys, node.values): - rebuilt_value = self.visit(value, newnode) - if not key: - # Python 3.5 and extended unpacking - rebuilt_key = nodes.DictUnpack( - rebuilt_value.lineno, rebuilt_value.col_offset, parent - ) - else: - rebuilt_key = self.visit(key, newnode) - yield rebuilt_key, rebuilt_value - - def visit_dict(self, node, parent): - """visit a Dict node by returning a fresh instance of it""" - newnode = nodes.Dict(node.lineno, node.col_offset, parent) - items = list(self._visit_dict_items(node, parent, newnode)) - newnode.postinit(items) - return newnode - - def visit_dictcomp(self, node, parent): - """visit a DictComp node by returning a fresh instance of it""" - newnode = nodes.DictComp(node.lineno, node.col_offset, parent) - newnode.postinit( - self.visit(node.key, newnode), - self.visit(node.value, newnode), - [self.visit(child, newnode) for child in node.generators], - ) - return newnode - - def visit_expr(self, node, parent): - """visit a Expr node by returning a fresh instance of it""" - newnode = nodes.Expr(node.lineno, node.col_offset, parent) - newnode.postinit(self.visit(node.value, newnode)) - return newnode - - # Not used in Python 3.8+. - def visit_ellipsis(self, node, parent): - """visit an Ellipsis node by returning a fresh instance of it""" - return nodes.Ellipsis( - getattr(node, "lineno", None), getattr(node, "col_offset", None), parent - ) - - def visit_emptynode(self, node, parent): - """visit an EmptyNode node by returning a fresh instance of it""" - return nodes.EmptyNode( - getattr(node, "lineno", None), getattr(node, "col_offset", None), parent - ) - - def visit_excepthandler(self, node, parent): - """visit an ExceptHandler node by returning a fresh instance of it""" - newnode = nodes.ExceptHandler(node.lineno, node.col_offset, parent) - if node.name: - name = self.visit_assignname(node, newnode, node.name) - else: - name = None - newnode.postinit( - _visit_or_none(node, "type", self, newnode), - name, - [self.visit(child, newnode) for child in node.body], - ) - return newnode - - def visit_exec(self, node, parent): - """visit an Exec node by returning a fresh instance of it""" - newnode = nodes.Exec(node.lineno, node.col_offset, parent) - newnode.postinit( - self.visit(node.body, newnode), - _visit_or_none(node, "globals", self, newnode), - _visit_or_none(node, "locals", self, newnode), - ) - return newnode - - # Not used in Python 3.8+. - def visit_extslice(self, node, parent): - """visit an ExtSlice node by returning a fresh instance of it""" - newnode = nodes.ExtSlice(parent=parent) - newnode.postinit([self.visit(dim, newnode) for dim in node.dims]) - return newnode - - def _visit_for(self, cls, node, parent): - """visit a For node by returning a fresh instance of it""" - newnode = cls(node.lineno, node.col_offset, parent) - type_annotation = self.check_type_comment(node, parent=newnode) - newnode.postinit( - target=self.visit(node.target, newnode), - iter=self.visit(node.iter, newnode), - body=[self.visit(child, newnode) for child in node.body], - orelse=[self.visit(child, newnode) for child in node.orelse], - type_annotation=type_annotation, - ) - return newnode - - def visit_for(self, node, parent): - return self._visit_for(nodes.For, node, parent) - - def visit_importfrom(self, node, parent): - """visit an ImportFrom node by returning a fresh instance of it""" - names = [(alias.name, alias.asname) for alias in node.names] - newnode = nodes.ImportFrom( - node.module or "", - names, - node.level or None, - getattr(node, "lineno", None), - getattr(node, "col_offset", None), - parent, - ) - # store From names to add them to locals after building - self._import_from_nodes.append(newnode) - return newnode - - def _visit_functiondef(self, cls, node, parent): - """visit an FunctionDef node to become astroid""" - self._global_names.append({}) - node, doc = self._get_doc(node) - - lineno = node.lineno - if PY38 and node.decorator_list: - # Python 3.8 sets the line number of a decorated function - # to be the actual line number of the function, but the - # previous versions expected the decorator's line number instead. - # We reset the function's line number to that of the - # first decorator to maintain backward compatibility. - # It's not ideal but this discrepancy was baked into - # the framework for *years*. - lineno = node.decorator_list[0].lineno - - newnode = cls(node.name, doc, lineno, node.col_offset, parent) - if node.decorator_list: - decorators = self.visit_decorators(node, newnode) - else: - decorators = None - if node.returns: - returns = self.visit(node.returns, newnode) - else: - returns = None - - type_comment_args = type_comment_returns = None - type_comment_annotation = self.check_function_type_comment(node) - if type_comment_annotation: - type_comment_returns, type_comment_args = type_comment_annotation - newnode.postinit( - args=self.visit(node.args, newnode), - body=[self.visit(child, newnode) for child in node.body], - decorators=decorators, - returns=returns, - type_comment_returns=type_comment_returns, - type_comment_args=type_comment_args, - ) - self._global_names.pop() - return newnode - - def visit_functiondef(self, node, parent): - return self._visit_functiondef(nodes.FunctionDef, node, parent) - - def visit_generatorexp(self, node, parent): - """visit a GeneratorExp node by returning a fresh instance of it""" - newnode = nodes.GeneratorExp(node.lineno, node.col_offset, parent) - newnode.postinit( - self.visit(node.elt, newnode), - [self.visit(child, newnode) for child in node.generators], - ) - return newnode - - def visit_attribute(self, node, parent): - """visit an Attribute node by returning a fresh instance of it""" - context = self._get_context(node) - if context == astroid.Del: - # FIXME : maybe we should reintroduce and visit_delattr ? - # for instance, deactivating assign_ctx - newnode = nodes.DelAttr(node.attr, node.lineno, node.col_offset, parent) - elif context == astroid.Store: - newnode = nodes.AssignAttr(node.attr, node.lineno, node.col_offset, parent) - # Prohibit a local save if we are in an ExceptHandler. - if not isinstance(parent, astroid.ExceptHandler): - self._delayed_assattr.append(newnode) - else: - newnode = nodes.Attribute(node.attr, node.lineno, node.col_offset, parent) - newnode.postinit(self.visit(node.value, newnode)) - return newnode - - def visit_global(self, node, parent): - """visit a Global node to become astroid""" - newnode = nodes.Global( - node.names, - getattr(node, "lineno", None), - getattr(node, "col_offset", None), - parent, - ) - if self._global_names: # global at the module level, no effect - for name in node.names: - self._global_names[-1].setdefault(name, []).append(newnode) - return newnode - - def visit_if(self, node, parent): - """visit an If node by returning a fresh instance of it""" - newnode = nodes.If(node.lineno, node.col_offset, parent) - newnode.postinit( - self.visit(node.test, newnode), - [self.visit(child, newnode) for child in node.body], - [self.visit(child, newnode) for child in node.orelse], - ) - return newnode - - def visit_ifexp(self, node, parent): - """visit a IfExp node by returning a fresh instance of it""" - newnode = nodes.IfExp(node.lineno, node.col_offset, parent) - newnode.postinit( - self.visit(node.test, newnode), - self.visit(node.body, newnode), - self.visit(node.orelse, newnode), - ) - return newnode - - def visit_import(self, node, parent): - """visit a Import node by returning a fresh instance of it""" - names = [(alias.name, alias.asname) for alias in node.names] - newnode = nodes.Import( - names, - getattr(node, "lineno", None), - getattr(node, "col_offset", None), - parent, - ) - # save import names in parent's locals: - for (name, asname) in newnode.names: - name = asname or name - parent.set_local(name.split(".")[0], newnode) - return newnode - - def visit_joinedstr(self, node, parent): - newnode = nodes.JoinedStr(node.lineno, node.col_offset, parent) - newnode.postinit([self.visit(child, newnode) for child in node.values]) - return newnode - - def visit_formattedvalue(self, node, parent): - newnode = nodes.FormattedValue(node.lineno, node.col_offset, parent) - newnode.postinit( - self.visit(node.value, newnode), - node.conversion, - _visit_or_none(node, "format_spec", self, newnode), - ) - return newnode - - def visit_namedexpr(self, node, parent): - newnode = nodes.NamedExpr(node.lineno, node.col_offset, parent) - newnode.postinit( - self.visit(node.target, newnode), self.visit(node.value, newnode) - ) - return newnode - - # Not used in Python 3.8+. - def visit_index(self, node, parent): - """visit a Index node by returning a fresh instance of it""" - newnode = nodes.Index(parent=parent) - newnode.postinit(self.visit(node.value, newnode)) - return newnode - - def visit_keyword(self, node, parent): - """visit a Keyword node by returning a fresh instance of it""" - newnode = nodes.Keyword(node.arg, parent=parent) - newnode.postinit(self.visit(node.value, newnode)) - return newnode - - def visit_lambda(self, node, parent): - """visit a Lambda node by returning a fresh instance of it""" - newnode = nodes.Lambda(node.lineno, node.col_offset, parent) - newnode.postinit(self.visit(node.args, newnode), self.visit(node.body, newnode)) - return newnode - - def visit_list(self, node, parent): - """visit a List node by returning a fresh instance of it""" - context = self._get_context(node) - newnode = nodes.List( - ctx=context, lineno=node.lineno, col_offset=node.col_offset, parent=parent - ) - newnode.postinit([self.visit(child, newnode) for child in node.elts]) - return newnode - - def visit_listcomp(self, node, parent): - """visit a ListComp node by returning a fresh instance of it""" - newnode = nodes.ListComp(node.lineno, node.col_offset, parent) - newnode.postinit( - self.visit(node.elt, newnode), - [self.visit(child, newnode) for child in node.generators], - ) - return newnode - - def visit_name(self, node, parent): - """visit a Name node by returning a fresh instance of it""" - context = self._get_context(node) - # True and False can be assigned to something in py2x, so we have to - # check first the context. - if context == astroid.Del: - newnode = nodes.DelName(node.id, node.lineno, node.col_offset, parent) - elif context == astroid.Store: - newnode = nodes.AssignName(node.id, node.lineno, node.col_offset, parent) - elif node.id in CONST_NAME_TRANSFORMS: - newnode = nodes.Const( - CONST_NAME_TRANSFORMS[node.id], - getattr(node, "lineno", None), - getattr(node, "col_offset", None), - parent, - ) - return newnode - else: - newnode = nodes.Name(node.id, node.lineno, node.col_offset, parent) - # XXX REMOVE me : - if context in (astroid.Del, astroid.Store): # 'Aug' ?? - self._save_assignment(newnode) - return newnode - - # Not used in Python 3.8+. - def visit_nameconstant(self, node, parent): - # in Python 3.4 we have NameConstant for True / False / None - return nodes.Const( - node.value, - getattr(node, "lineno", None), - getattr(node, "col_offset", None), - parent, - ) - - def visit_nonlocal(self, node, parent): - """visit a Nonlocal node and return a new instance of it""" - return nodes.Nonlocal( - node.names, - getattr(node, "lineno", None), - getattr(node, "col_offset", None), - parent, - ) - - def visit_constant(self, node, parent): - """visit a Constant node by returning a fresh instance of Const""" - return nodes.Const( - node.value, - getattr(node, "lineno", None), - getattr(node, "col_offset", None), - parent, - ) - - # Not used in Python 3.8+. - def visit_str(self, node, parent): - """visit a String/Bytes node by returning a fresh instance of Const""" - return nodes.Const( - node.s, - getattr(node, "lineno", None), - getattr(node, "col_offset", None), - parent, - ) - - visit_bytes = visit_str - - # Not used in Python 3.8+. - def visit_num(self, node, parent): - """visit a Num node by returning a fresh instance of Const""" - return nodes.Const( - node.n, - getattr(node, "lineno", None), - getattr(node, "col_offset", None), - parent, - ) - - def visit_pass(self, node, parent): - """visit a Pass node by returning a fresh instance of it""" - return nodes.Pass(node.lineno, node.col_offset, parent) - - def visit_print(self, node, parent): - """visit a Print node by returning a fresh instance of it""" - newnode = nodes.Print(node.nl, node.lineno, node.col_offset, parent) - newnode.postinit( - _visit_or_none(node, "dest", self, newnode), - [self.visit(child, newnode) for child in node.values], - ) - return newnode - - def visit_raise(self, node, parent): - """visit a Raise node by returning a fresh instance of it""" - newnode = nodes.Raise(node.lineno, node.col_offset, parent) - # no traceback; anyway it is not used in Pylint - newnode.postinit( - _visit_or_none(node, "exc", self, newnode), - _visit_or_none(node, "cause", self, newnode), - ) - return newnode - - def visit_return(self, node, parent): - """visit a Return node by returning a fresh instance of it""" - newnode = nodes.Return(node.lineno, node.col_offset, parent) - if node.value is not None: - newnode.postinit(self.visit(node.value, newnode)) - return newnode - - def visit_set(self, node, parent): - """visit a Set node by returning a fresh instance of it""" - newnode = nodes.Set(node.lineno, node.col_offset, parent) - newnode.postinit([self.visit(child, newnode) for child in node.elts]) - return newnode - - def visit_setcomp(self, node, parent): - """visit a SetComp node by returning a fresh instance of it""" - newnode = nodes.SetComp(node.lineno, node.col_offset, parent) - newnode.postinit( - self.visit(node.elt, newnode), - [self.visit(child, newnode) for child in node.generators], - ) - return newnode - - def visit_slice(self, node, parent): - """visit a Slice node by returning a fresh instance of it""" - newnode = nodes.Slice(parent=parent) - newnode.postinit( - _visit_or_none(node, "lower", self, newnode), - _visit_or_none(node, "upper", self, newnode), - _visit_or_none(node, "step", self, newnode), - ) - return newnode - - def visit_subscript(self, node, parent): - """visit a Subscript node by returning a fresh instance of it""" - context = self._get_context(node) - newnode = nodes.Subscript( - ctx=context, lineno=node.lineno, col_offset=node.col_offset, parent=parent - ) - newnode.postinit( - self.visit(node.value, newnode), self.visit(node.slice, newnode) - ) - return newnode - - def visit_starred(self, node, parent): - """visit a Starred node and return a new instance of it""" - context = self._get_context(node) - newnode = nodes.Starred( - ctx=context, lineno=node.lineno, col_offset=node.col_offset, parent=parent - ) - newnode.postinit(self.visit(node.value, newnode)) - return newnode - - def visit_tryexcept(self, node, parent): - """visit a TryExcept node by returning a fresh instance of it""" - newnode = nodes.TryExcept(node.lineno, node.col_offset, parent) - newnode.postinit( - [self.visit(child, newnode) for child in node.body], - [self.visit(child, newnode) for child in node.handlers], - [self.visit(child, newnode) for child in node.orelse], - ) - return newnode - - def visit_try(self, node, parent): - # python 3.3 introduce a new Try node replacing - # TryFinally/TryExcept nodes - if node.finalbody: - newnode = nodes.TryFinally(node.lineno, node.col_offset, parent) - if node.handlers: - body = [self.visit_tryexcept(node, newnode)] - else: - body = [self.visit(child, newnode) for child in node.body] - newnode.postinit(body, [self.visit(n, newnode) for n in node.finalbody]) - return newnode - if node.handlers: - return self.visit_tryexcept(node, parent) - return None - - def visit_tryfinally(self, node, parent): - """visit a TryFinally node by returning a fresh instance of it""" - newnode = nodes.TryFinally(node.lineno, node.col_offset, parent) - newnode.postinit( - [self.visit(child, newnode) for child in node.body], - [self.visit(n, newnode) for n in node.finalbody], - ) - return newnode - - def visit_tuple(self, node, parent): - """visit a Tuple node by returning a fresh instance of it""" - context = self._get_context(node) - newnode = nodes.Tuple( - ctx=context, lineno=node.lineno, col_offset=node.col_offset, parent=parent - ) - newnode.postinit([self.visit(child, newnode) for child in node.elts]) - return newnode - - def visit_unaryop(self, node, parent): - """visit a UnaryOp node by returning a fresh instance of it""" - newnode = nodes.UnaryOp( - self._parser_module.unary_op_classes[node.op.__class__], - node.lineno, - node.col_offset, - parent, - ) - newnode.postinit(self.visit(node.operand, newnode)) - return newnode - - def visit_while(self, node, parent): - """visit a While node by returning a fresh instance of it""" - newnode = nodes.While(node.lineno, node.col_offset, parent) - newnode.postinit( - self.visit(node.test, newnode), - [self.visit(child, newnode) for child in node.body], - [self.visit(child, newnode) for child in node.orelse], - ) - return newnode - - def _visit_with(self, cls, node, parent): - newnode = cls(node.lineno, node.col_offset, parent) - - def visit_child(child): - expr = self.visit(child.context_expr, newnode) - var = _visit_or_none(child, "optional_vars", self, newnode) - return expr, var - - type_annotation = self.check_type_comment(node, parent=newnode) - newnode.postinit( - items=[visit_child(child) for child in node.items], - body=[self.visit(child, newnode) for child in node.body], - type_annotation=type_annotation, - ) - return newnode - - def visit_with(self, node, parent): - return self._visit_with(nodes.With, node, parent) - - def visit_yield(self, node, parent): - """visit a Yield node by returning a fresh instance of it""" - newnode = nodes.Yield(node.lineno, node.col_offset, parent) - if node.value is not None: - newnode.postinit(self.visit(node.value, newnode)) - return newnode - - def visit_yieldfrom(self, node, parent): - newnode = nodes.YieldFrom(node.lineno, node.col_offset, parent) - if node.value is not None: - newnode.postinit(self.visit(node.value, newnode)) - return newnode diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/scoped_nodes.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/scoped_nodes.py deleted file mode 100644 index 8561e74..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/scoped_nodes.py +++ /dev/null @@ -1,2927 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright (c) 2006-2014 LOGILAB S.A. (Paris, FRANCE) -# Copyright (c) 2010 Daniel Harding -# Copyright (c) 2011, 2013-2015 Google, Inc. -# Copyright (c) 2013-2020 Claudiu Popa -# Copyright (c) 2013 Phil Schaf -# Copyright (c) 2014 Eevee (Alex Munroe) -# Copyright (c) 2015-2016 Florian Bruhin -# Copyright (c) 2015-2016 Ceridwen -# Copyright (c) 2015 Rene Zhang -# Copyright (c) 2015 Philip Lorenz -# Copyright (c) 2016-2017 Derek Gustafson -# Copyright (c) 2017-2018 Bryce Guinta -# Copyright (c) 2017-2018 Ashley Whetter -# Copyright (c) 2017 Łukasz Rogalski -# Copyright (c) 2017 David Euresti -# Copyright (c) 2018-2019 Nick Drozd -# Copyright (c) 2018 Ville Skyttä -# Copyright (c) 2018 Anthony Sottile -# Copyright (c) 2018 HoverHell -# Copyright (c) 2019 Hugo van Kemenade -# Copyright (c) 2019 Peter de Blanc - -# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html -# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER - - -""" -This module contains the classes for "scoped" node, i.e. which are opening a -new local scope in the language definition : Module, ClassDef, FunctionDef (and -Lambda, GeneratorExp, DictComp and SetComp to some extent). -""" - -import builtins -import sys -import io -import itertools -from typing import Optional, List - -from astroid import bases -from astroid import context as contextmod -from astroid import exceptions -from astroid import decorators as decorators_mod -from astroid.interpreter import objectmodel -from astroid.interpreter import dunder_lookup -from astroid import manager -from astroid import mixins -from astroid import node_classes -from astroid import util - - -BUILTINS = builtins.__name__ -ITER_METHODS = ("__iter__", "__getitem__") -EXCEPTION_BASE_CLASSES = frozenset({"Exception", "BaseException"}) -objects = util.lazy_import("objects") -BUILTIN_DESCRIPTORS = frozenset( - {"classmethod", "staticmethod", "builtins.classmethod", "builtins.staticmethod"} -) - - -def _c3_merge(sequences, cls, context): - """Merges MROs in *sequences* to a single MRO using the C3 algorithm. - - Adapted from http://www.python.org/download/releases/2.3/mro/. - - """ - result = [] - while True: - sequences = [s for s in sequences if s] # purge empty sequences - if not sequences: - return result - for s1 in sequences: # find merge candidates among seq heads - candidate = s1[0] - for s2 in sequences: - if candidate in s2[1:]: - candidate = None - break # reject the current head, it appears later - else: - break - if not candidate: - # Show all the remaining bases, which were considered as - # candidates for the next mro sequence. - raise exceptions.InconsistentMroError( - message="Cannot create a consistent method resolution order " - "for MROs {mros} of class {cls!r}.", - mros=sequences, - cls=cls, - context=context, - ) - - result.append(candidate) - # remove the chosen candidate - for seq in sequences: - if seq[0] == candidate: - del seq[0] - return None - - -def clean_duplicates_mro(sequences, cls, context): - for sequence in sequences: - names = [ - (node.lineno, node.qname()) if node.name else None for node in sequence - ] - last_index = dict(map(reversed, enumerate(names))) - if names and names[0] is not None and last_index[names[0]] != 0: - raise exceptions.DuplicateBasesError( - message="Duplicates found in MROs {mros} for {cls!r}.", - mros=sequences, - cls=cls, - context=context, - ) - yield [ - node - for i, (node, name) in enumerate(zip(sequence, names)) - if name is None or last_index[name] == i - ] - - -def function_to_method(n, klass): - if isinstance(n, FunctionDef): - if n.type == "classmethod": - return bases.BoundMethod(n, klass) - if n.type == "property": - return n - if n.type != "staticmethod": - return bases.UnboundMethod(n) - return n - - -MANAGER = manager.AstroidManager() - - -def builtin_lookup(name): - """lookup a name into the builtin module - return the list of matching statements and the astroid for the builtin - module - """ - builtin_astroid = MANAGER.ast_from_module(builtins) - if name == "__dict__": - return builtin_astroid, () - try: - stmts = builtin_astroid.locals[name] - except KeyError: - stmts = () - return builtin_astroid, stmts - - -# TODO move this Mixin to mixins.py; problem: 'FunctionDef' in _scope_lookup -class LocalsDictNodeNG(node_classes.LookupMixIn, node_classes.NodeNG): - """ this class provides locals handling common to Module, FunctionDef - and ClassDef nodes, including a dict like interface for direct access - to locals information - """ - - # attributes below are set by the builder module or by raw factories - - locals = {} - """A map of the name of a local variable to the node defining the local. - - :type: dict(str, NodeNG) - """ - - def qname(self): - """Get the 'qualified' name of the node. - - For example: module.name, module.class.name ... - - :returns: The qualified name. - :rtype: str - """ - # pylint: disable=no-member; github.com/pycqa/astroid/issues/278 - if self.parent is None: - return self.name - return "%s.%s" % (self.parent.frame().qname(), self.name) - - def frame(self): - """The first parent frame node. - - A frame node is a :class:`Module`, :class:`FunctionDef`, - or :class:`ClassDef`. - - :returns: The first parent frame node. - :rtype: Module or FunctionDef or ClassDef - """ - return self - - def scope(self): - """The first parent node defining a new scope. - - :returns: The first parent scope node. - :rtype: Module or FunctionDef or ClassDef or Lambda or GenExpr - """ - return self - - def _scope_lookup(self, node, name, offset=0): - """XXX method for interfacing the scope lookup""" - try: - stmts = node._filter_stmts(self.locals[name], self, offset) - except KeyError: - stmts = () - if stmts: - return self, stmts - if self.parent: # i.e. not Module - # nested scope: if parent scope is a function, that's fine - # else jump to the module - pscope = self.parent.scope() - if not pscope.is_function: - pscope = pscope.root() - return pscope.scope_lookup(node, name) - return builtin_lookup(name) # Module - - def set_local(self, name, stmt): - """Define that the given name is declared in the given statement node. - - .. seealso:: :meth:`scope` - - :param name: The name that is being defined. - :type name: str - - :param stmt: The statement that defines the given name. - :type stmt: NodeNG - """ - # assert not stmt in self.locals.get(name, ()), (self, stmt) - self.locals.setdefault(name, []).append(stmt) - - __setitem__ = set_local - - def _append_node(self, child): - """append a child, linking it in the tree""" - # pylint: disable=no-member; depending by the class - # which uses the current class as a mixin or base class. - # It's rewritten in 2.0, so it makes no sense for now - # to spend development time on it. - self.body.append(child) - child.parent = self - - def add_local_node(self, child_node, name=None): - """Append a child that should alter the locals of this scope node. - - :param child_node: The child node that will alter locals. - :type child_node: NodeNG - - :param name: The name of the local that will be altered by - the given child node. - :type name: str or None - """ - if name != "__class__": - # add __class__ node as a child will cause infinite recursion later! - self._append_node(child_node) - self.set_local(name or child_node.name, child_node) - - def __getitem__(self, item): - """The first node the defines the given local. - - :param item: The name of the locally defined object. - :type item: str - - :raises KeyError: If the name is not defined. - """ - return self.locals[item][0] - - def __iter__(self): - """Iterate over the names of locals defined in this scoped node. - - :returns: The names of the defined locals. - :rtype: iterable(str) - """ - return iter(self.keys()) - - def keys(self): - """The names of locals defined in this scoped node. - - :returns: The names of the defined locals. - :rtype: list(str) - """ - return list(self.locals.keys()) - - def values(self): - """The nodes that define the locals in this scoped node. - - :returns: The nodes that define locals. - :rtype: list(NodeNG) - """ - return [self[key] for key in self.keys()] - - def items(self): - """Get the names of the locals and the node that defines the local. - - :returns: The names of locals and their associated node. - :rtype: list(tuple(str, NodeNG)) - """ - return list(zip(self.keys(), self.values())) - - def __contains__(self, name): - """Check if a local is defined in this scope. - - :param name: The name of the local to check for. - :type name: str - - :returns: True if this node has a local of the given name, - False otherwise. - :rtype: bool - """ - return name in self.locals - - -class Module(LocalsDictNodeNG): - """Class representing an :class:`ast.Module` node. - - >>> node = astroid.extract_node('import astroid') - >>> node - - >>> node.parent - - """ - - _astroid_fields = ("body",) - - fromlineno = 0 - """The first line that this node appears on in the source code. - - :type: int or None - """ - lineno = 0 - """The line that this node appears on in the source code. - - :type: int or None - """ - - # attributes below are set by the builder module or by raw factories - - file = None - """The path to the file that this ast has been extracted from. - - This will be ``None`` when the representation has been built from a - built-in module. - - :type: str or None - """ - file_bytes = None - """The string/bytes that this ast was built from. - - :type: str or bytes or None - """ - file_encoding = None - """The encoding of the source file. - - This is used to get unicode out of a source file. - Python 2 only. - - :type: str or None - """ - name = None - """The name of the module. - - :type: str or None - """ - pure_python = None - """Whether the ast was built from source. - - :type: bool or None - """ - package = None - """Whether the node represents a package or a module. - - :type: bool or None - """ - globals = None - """A map of the name of a global variable to the node defining the global. - - :type: dict(str, NodeNG) - """ - - # Future imports - future_imports = None - """The imports from ``__future__``. - - :type: set(str) or None - """ - special_attributes = objectmodel.ModuleModel() - """The names of special attributes that this module has. - - :type: objectmodel.ModuleModel - """ - - # names of module attributes available through the global scope - scope_attrs = {"__name__", "__doc__", "__file__", "__path__", "__package__"} - """The names of module attributes available through the global scope. - - :type: str(str) - """ - - _other_fields = ( - "name", - "doc", - "file", - "path", - "package", - "pure_python", - "future_imports", - ) - _other_other_fields = ("locals", "globals") - - def __init__( - self, - name, - doc, - file=None, - path: Optional[List[str]] = None, - package=None, - parent=None, - pure_python=True, - ): - """ - :param name: The name of the module. - :type name: str - - :param doc: The module docstring. - :type doc: str - - :param file: The path to the file that this ast has been extracted from. - :type file: str or None - - :param path: - :type path: Optional[List[str]] - - :param package: Whether the node represents a package or a module. - :type package: bool or None - - :param parent: The parent node in the syntax tree. - :type parent: NodeNG or None - - :param pure_python: Whether the ast was built from source. - :type pure_python: bool or None - """ - self.name = name - self.doc = doc - self.file = file - self.path = path - self.package = package - self.parent = parent - self.pure_python = pure_python - self.locals = self.globals = {} - """A map of the name of a local variable to the node defining the local. - - :type: dict(str, NodeNG) - """ - self.body = [] - """The contents of the module. - - :type: list(NodeNG) or None - """ - self.future_imports = set() - - # pylint: enable=redefined-builtin - - def postinit(self, body=None): - """Do some setup after initialisation. - - :param body: The contents of the module. - :type body: list(NodeNG) or None - """ - self.body = body - - def _get_stream(self): - if self.file_bytes is not None: - return io.BytesIO(self.file_bytes) - if self.file is not None: - stream = open(self.file, "rb") - return stream - return None - - def stream(self): - """Get a stream to the underlying file or bytes. - - :type: file or io.BytesIO or None - """ - return self._get_stream() - - def block_range(self, lineno): - """Get a range from where this node starts to where this node ends. - - :param lineno: Unused. - :type lineno: int - - :returns: The range of line numbers that this node belongs to. - :rtype: tuple(int, int) - """ - return self.fromlineno, self.tolineno - - def scope_lookup(self, node, name, offset=0): - """Lookup where the given variable is assigned. - - :param node: The node to look for assignments up to. - Any assignments after the given node are ignored. - :type node: NodeNG - - :param name: The name of the variable to find assignments for. - :type name: str - - :param offset: The line offset to filter statements up to. - :type offset: int - - :returns: This scope node and the list of assignments associated to the - given name according to the scope where it has been found (locals, - globals or builtin). - :rtype: tuple(str, list(NodeNG)) - """ - if name in self.scope_attrs and name not in self.locals: - try: - return self, self.getattr(name) - except exceptions.AttributeInferenceError: - return self, () - return self._scope_lookup(node, name, offset) - - def pytype(self): - """Get the name of the type that this node represents. - - :returns: The name of the type. - :rtype: str - """ - return "%s.module" % BUILTINS - - def display_type(self): - """A human readable type of this node. - - :returns: The type of this node. - :rtype: str - """ - return "Module" - - def getattr(self, name, context=None, ignore_locals=False): - if not name: - raise exceptions.AttributeInferenceError( - target=self, attribute=name, context=context - ) - - result = [] - name_in_locals = name in self.locals - - if name in self.special_attributes and not ignore_locals and not name_in_locals: - result = [self.special_attributes.lookup(name)] - elif not ignore_locals and name_in_locals: - result = self.locals[name] - elif self.package: - try: - result = [self.import_module(name, relative_only=True)] - except (exceptions.AstroidBuildingError, SyntaxError) as exc: - raise exceptions.AttributeInferenceError( - target=self, attribute=name, context=context - ) from exc - result = [n for n in result if not isinstance(n, node_classes.DelName)] - if result: - return result - raise exceptions.AttributeInferenceError( - target=self, attribute=name, context=context - ) - - def igetattr(self, name, context=None): - """Infer the possible values of the given variable. - - :param name: The name of the variable to infer. - :type name: str - - :returns: The inferred possible values. - :rtype: iterable(NodeNG) or None - """ - # set lookup name since this is necessary to infer on import nodes for - # instance - context = contextmod.copy_context(context) - context.lookupname = name - try: - return bases._infer_stmts(self.getattr(name, context), context, frame=self) - except exceptions.AttributeInferenceError as error: - raise exceptions.InferenceError( - error.message, target=self, attribute=name, context=context - ) from error - - def fully_defined(self): - """Check if this module has been build from a .py file. - - If so, the module contains a complete representation, - including the code. - - :returns: True if the module has been built from a .py file. - :rtype: bool - """ - return self.file is not None and self.file.endswith(".py") - - def statement(self): - """The first parent node, including self, marked as statement node. - - :returns: The first parent statement. - :rtype: NodeNG - """ - return self - - def previous_sibling(self): - """The previous sibling statement. - - :returns: The previous sibling statement node. - :rtype: NodeNG or None - """ - - def next_sibling(self): - """The next sibling statement node. - - :returns: The next sibling statement node. - :rtype: NodeNG or None - """ - - _absolute_import_activated = True - - def absolute_import_activated(self): - """Whether :pep:`328` absolute import behaviour has been enabled. - - :returns: True if :pep:`328` has been enabled, False otherwise. - :rtype: bool - """ - return self._absolute_import_activated - - def import_module(self, modname, relative_only=False, level=None): - """Get the ast for a given module as if imported from this module. - - :param modname: The name of the module to "import". - :type modname: str - - :param relative_only: Whether to only consider relative imports. - :type relative_only: bool - - :param level: The level of relative import. - :type level: int or None - - :returns: The imported module ast. - :rtype: NodeNG - """ - if relative_only and level is None: - level = 0 - absmodname = self.relative_to_absolute_name(modname, level) - - try: - return MANAGER.ast_from_module_name(absmodname) - except exceptions.AstroidBuildingError: - # we only want to import a sub module or package of this module, - # skip here - if relative_only: - raise - return MANAGER.ast_from_module_name(modname) - - def relative_to_absolute_name(self, modname, level): - """Get the absolute module name for a relative import. - - The relative import can be implicit or explicit. - - :param modname: The module name to convert. - :type modname: str - - :param level: The level of relative import. - :type level: int - - :returns: The absolute module name. - :rtype: str - - :raises TooManyLevelsError: When the relative import refers to a - module too far above this one. - """ - # XXX this returns non sens when called on an absolute import - # like 'pylint.checkers.astroid.utils' - # XXX doesn't return absolute name if self.name isn't absolute name - if self.absolute_import_activated() and level is None: - return modname - if level: - if self.package: - level = level - 1 - if level and self.name.count(".") < level: - raise exceptions.TooManyLevelsError(level=level, name=self.name) - - package_name = self.name.rsplit(".", level)[0] - elif self.package: - package_name = self.name - else: - package_name = self.name.rsplit(".", 1)[0] - - if package_name: - if not modname: - return package_name - return "%s.%s" % (package_name, modname) - return modname - - def wildcard_import_names(self): - """The list of imported names when this module is 'wildcard imported'. - - It doesn't include the '__builtins__' name which is added by the - current CPython implementation of wildcard imports. - - :returns: The list of imported names. - :rtype: list(str) - """ - # We separate the different steps of lookup in try/excepts - # to avoid catching too many Exceptions - default = [name for name in self.keys() if not name.startswith("_")] - try: - all_values = self["__all__"] - except KeyError: - return default - - try: - explicit = next(all_values.assigned_stmts()) - except exceptions.InferenceError: - return default - except AttributeError: - # not an assignment node - # XXX infer? - return default - - # Try our best to detect the exported name. - inferred = [] - try: - explicit = next(explicit.infer()) - except exceptions.InferenceError: - return default - if not isinstance(explicit, (node_classes.Tuple, node_classes.List)): - return default - - str_const = lambda node: ( - isinstance(node, node_classes.Const) and isinstance(node.value, str) - ) - for node in explicit.elts: - if str_const(node): - inferred.append(node.value) - else: - try: - inferred_node = next(node.infer()) - except exceptions.InferenceError: - continue - if str_const(inferred_node): - inferred.append(inferred_node.value) - return inferred - - def public_names(self): - """The list of the names that are publicly available in this module. - - :returns: The list of publc names. - :rtype: list(str) - """ - return [name for name in self.keys() if not name.startswith("_")] - - def bool_value(self, context=None): - """Determine the boolean value of this node. - - :returns: The boolean value of this node. - For a :class:`Module` this is always ``True``. - :rtype: bool - """ - return True - - def get_children(self): - yield from self.body - - -class ComprehensionScope(LocalsDictNodeNG): - """Scoping for different types of comprehensions.""" - - def frame(self): - """The first parent frame node. - - A frame node is a :class:`Module`, :class:`FunctionDef`, - or :class:`ClassDef`. - - :returns: The first parent frame node. - :rtype: Module or FunctionDef or ClassDef - """ - return self.parent.frame() - - scope_lookup = LocalsDictNodeNG._scope_lookup - - -class GeneratorExp(ComprehensionScope): - """Class representing an :class:`ast.GeneratorExp` node. - - >>> node = astroid.extract_node('(thing for thing in things if thing)') - >>> node - - """ - - _astroid_fields = ("elt", "generators") - _other_other_fields = ("locals",) - elt = None - """The element that forms the output of the expression. - - :type: NodeNG or None - """ - generators = None - """The generators that are looped through. - - :type: list(Comprehension) or None - """ - - def __init__(self, lineno=None, col_offset=None, parent=None): - """ - :param lineno: The line that this node appears on in the source code. - :type lineno: int or None - - :param col_offset: The column that this node appears on in the - source code. - :type col_offset: int or None - - :param parent: The parent node in the syntax tree. - :type parent: NodeNG or None - """ - self.locals = {} - """A map of the name of a local variable to the node defining the local. - - :type: dict(str, NodeNG) - """ - - super().__init__(lineno, col_offset, parent) - - def postinit(self, elt=None, generators=None): - """Do some setup after initialisation. - - :param elt: The element that forms the output of the expression. - :type elt: NodeNG or None - - :param generators: The generators that are looped through. - :type generators: list(Comprehension) or None - """ - self.elt = elt - if generators is None: - self.generators = [] - else: - self.generators = generators - - def bool_value(self, context=None): - """Determine the boolean value of this node. - - :returns: The boolean value of this node. - For a :class:`GeneratorExp` this is always ``True``. - :rtype: bool - """ - return True - - def get_children(self): - yield self.elt - - yield from self.generators - - -class DictComp(ComprehensionScope): - """Class representing an :class:`ast.DictComp` node. - - >>> node = astroid.extract_node('{k:v for k, v in things if k > v}') - >>> node - - """ - - _astroid_fields = ("key", "value", "generators") - _other_other_fields = ("locals",) - key = None - """What produces the keys. - - :type: NodeNG or None - """ - value = None - """What produces the values. - - :type: NodeNG or None - """ - generators = None - """The generators that are looped through. - - :type: list(Comprehension) or None - """ - - def __init__(self, lineno=None, col_offset=None, parent=None): - """ - :param lineno: The line that this node appears on in the source code. - :type lineno: int or None - - :param col_offset: The column that this node appears on in the - source code. - :type col_offset: int or None - - :param parent: The parent node in the syntax tree. - :type parent: NodeNG or None - """ - self.locals = {} - """A map of the name of a local variable to the node defining the local. - - :type: dict(str, NodeNG) - """ - - super().__init__(lineno, col_offset, parent) - - def postinit(self, key=None, value=None, generators=None): - """Do some setup after initialisation. - - :param key: What produces the keys. - :type key: NodeNG or None - - :param value: What produces the values. - :type value: NodeNG or None - - :param generators: The generators that are looped through. - :type generators: list(Comprehension) or None - """ - self.key = key - self.value = value - if generators is None: - self.generators = [] - else: - self.generators = generators - - def bool_value(self, context=None): - """Determine the boolean value of this node. - - :returns: The boolean value of this node. - For a :class:`DictComp` this is always :class:`Uninferable`. - :rtype: Uninferable - """ - return util.Uninferable - - def get_children(self): - yield self.key - yield self.value - - yield from self.generators - - -class SetComp(ComprehensionScope): - """Class representing an :class:`ast.SetComp` node. - - >>> node = astroid.extract_node('{thing for thing in things if thing}') - >>> node - - """ - - _astroid_fields = ("elt", "generators") - _other_other_fields = ("locals",) - elt = None - """The element that forms the output of the expression. - - :type: NodeNG or None - """ - generators = None - """The generators that are looped through. - - :type: list(Comprehension) or None - """ - - def __init__(self, lineno=None, col_offset=None, parent=None): - """ - :param lineno: The line that this node appears on in the source code. - :type lineno: int or None - - :param col_offset: The column that this node appears on in the - source code. - :type col_offset: int or None - - :param parent: The parent node in the syntax tree. - :type parent: NodeNG or None - """ - self.locals = {} - """A map of the name of a local variable to the node defining the local. - - :type: dict(str, NodeNG) - """ - - super().__init__(lineno, col_offset, parent) - - def postinit(self, elt=None, generators=None): - """Do some setup after initialisation. - - :param elt: The element that forms the output of the expression. - :type elt: NodeNG or None - - :param generators: The generators that are looped through. - :type generators: list(Comprehension) or None - """ - self.elt = elt - if generators is None: - self.generators = [] - else: - self.generators = generators - - def bool_value(self, context=None): - """Determine the boolean value of this node. - - :returns: The boolean value of this node. - For a :class:`SetComp` this is always :class:`Uninferable`. - :rtype: Uninferable - """ - return util.Uninferable - - def get_children(self): - yield self.elt - - yield from self.generators - - -class _ListComp(node_classes.NodeNG): - """Class representing an :class:`ast.ListComp` node. - - >>> node = astroid.extract_node('[thing for thing in things if thing]') - >>> node - - """ - - _astroid_fields = ("elt", "generators") - elt = None - """The element that forms the output of the expression. - - :type: NodeNG or None - """ - generators = None - """The generators that are looped through. - - :type: list(Comprehension) or None - """ - - def postinit(self, elt=None, generators=None): - """Do some setup after initialisation. - - :param elt: The element that forms the output of the expression. - :type elt: NodeNG or None - - :param generators: The generators that are looped through. - :type generators: list(Comprehension) or None - """ - self.elt = elt - self.generators = generators - - def bool_value(self, context=None): - """Determine the boolean value of this node. - - :returns: The boolean value of this node. - For a :class:`ListComp` this is always :class:`Uninferable`. - :rtype: Uninferable - """ - return util.Uninferable - - def get_children(self): - yield self.elt - - yield from self.generators - - -class ListComp(_ListComp, ComprehensionScope): - """Class representing an :class:`ast.ListComp` node. - - >>> node = astroid.extract_node('[thing for thing in things if thing]') - >>> node - - """ - - _other_other_fields = ("locals",) - - def __init__(self, lineno=None, col_offset=None, parent=None): - self.locals = {} - """A map of the name of a local variable to the node defining it. - - :type: dict(str, NodeNG) - """ - - super().__init__(lineno, col_offset, parent) - - -def _infer_decorator_callchain(node): - """Detect decorator call chaining and see if the end result is a - static or a classmethod. - """ - if not isinstance(node, FunctionDef): - return None - if not node.parent: - return None - try: - result = next(node.infer_call_result(node.parent)) - except exceptions.InferenceError: - return None - if isinstance(result, bases.Instance): - result = result._proxied - if isinstance(result, ClassDef): - if result.is_subtype_of("%s.classmethod" % BUILTINS): - return "classmethod" - if result.is_subtype_of("%s.staticmethod" % BUILTINS): - return "staticmethod" - if isinstance(result, FunctionDef): - if not result.decorators: - return None - # Determine if this function is decorated with one of the builtin descriptors we want. - for decorator in result.decorators.nodes: - if isinstance(decorator, node_classes.Name): - if decorator.name in BUILTIN_DESCRIPTORS: - return decorator.name - if ( - isinstance(decorator, node_classes.Attribute) - and isinstance(decorator.expr, node_classes.Name) - and decorator.expr.name == BUILTINS - and decorator.attrname in BUILTIN_DESCRIPTORS - ): - return decorator.attrname - return None - - -class Lambda(mixins.FilterStmtsMixin, LocalsDictNodeNG): - """Class representing an :class:`ast.Lambda` node. - - >>> node = astroid.extract_node('lambda arg: arg + 1') - >>> node - l.1 at 0x7f23b2e41518> - """ - - _astroid_fields = ("args", "body") - _other_other_fields = ("locals",) - name = "" - is_lambda = True - - def implicit_parameters(self): - return 0 - - # function's type, 'function' | 'method' | 'staticmethod' | 'classmethod' - @property - def type(self): - """Whether this is a method or function. - - :returns: 'method' if this is a method, 'function' otherwise. - :rtype: str - """ - # pylint: disable=no-member - if self.args.arguments and self.args.arguments[0].name == "self": - if isinstance(self.parent.scope(), ClassDef): - return "method" - return "function" - - def __init__(self, lineno=None, col_offset=None, parent=None): - """ - :param lineno: The line that this node appears on in the source code. - :type lineno: int or None - - :param col_offset: The column that this node appears on in the - source code. - :type col_offset: int or None - - :param parent: The parent node in the syntax tree. - :type parent: NodeNG or None - """ - self.locals = {} - """A map of the name of a local variable to the node defining it. - - :type: dict(str, NodeNG) - """ - - self.args = [] - """The arguments that the function takes. - - :type: Arguments or list - """ - - self.body = [] - """The contents of the function body. - - :type: list(NodeNG) - """ - - super().__init__(lineno, col_offset, parent) - - def postinit(self, args, body): - """Do some setup after initialisation. - - :param args: The arguments that the function takes. - :type args: Arguments - - :param body: The contents of the function body. - :type body: list(NodeNG) - """ - self.args = args - self.body = body - - def pytype(self): - """Get the name of the type that this node represents. - - :returns: The name of the type. - :rtype: str - """ - if "method" in self.type: - return "%s.instancemethod" % BUILTINS - return "%s.function" % BUILTINS - - def display_type(self): - """A human readable type of this node. - - :returns: The type of this node. - :rtype: str - """ - if "method" in self.type: - return "Method" - return "Function" - - def callable(self): - """Whether this node defines something that is callable. - - :returns: True if this defines something that is callable, - False otherwise. - For a :class:`Lambda` this is always ``True``. - :rtype: bool - """ - return True - - def argnames(self): - """Get the names of each of the arguments. - - :returns: The names of the arguments. - :rtype: list(str) - """ - # pylint: disable=no-member; github.com/pycqa/astroid/issues/291 - # args is in fact redefined later on by postinit. Can't be changed - # to None due to a strong interaction between Lambda and FunctionDef. - - if self.args.arguments: # maybe None with builtin functions - names = _rec_get_names(self.args.arguments) - else: - names = [] - if self.args.vararg: - names.append(self.args.vararg) - if self.args.kwarg: - names.append(self.args.kwarg) - return names - - def infer_call_result(self, caller, context=None): - """Infer what the function returns when called. - - :param caller: Unused - :type caller: object - """ - # pylint: disable=no-member; github.com/pycqa/astroid/issues/291 - # args is in fact redefined later on by postinit. Can't be changed - # to None due to a strong interaction between Lambda and FunctionDef. - return self.body.infer(context) - - def scope_lookup(self, node, name, offset=0): - """Lookup where the given names is assigned. - - :param node: The node to look for assignments up to. - Any assignments after the given node are ignored. - :type node: NodeNG - - :param name: The name to find assignments for. - :type name: str - - :param offset: The line offset to filter statements up to. - :type offset: int - - :returns: This scope node and the list of assignments associated to the - given name according to the scope where it has been found (locals, - globals or builtin). - :rtype: tuple(str, list(NodeNG)) - """ - # pylint: disable=no-member; github.com/pycqa/astroid/issues/291 - # args is in fact redefined later on by postinit. Can't be changed - # to None due to a strong interaction between Lambda and FunctionDef. - - if node in self.args.defaults or node in self.args.kw_defaults: - frame = self.parent.frame() - # line offset to avoid that def func(f=func) resolve the default - # value to the defined function - offset = -1 - else: - # check this is not used in function decorators - frame = self - return frame._scope_lookup(node, name, offset) - - def bool_value(self, context=None): - """Determine the boolean value of this node. - - :returns: The boolean value of this node. - For a :class:`Lambda` this is always ``True``. - :rtype: bool - """ - return True - - def get_children(self): - yield self.args - yield self.body - - -class FunctionDef(mixins.MultiLineBlockMixin, node_classes.Statement, Lambda): - """Class representing an :class:`ast.FunctionDef`. - - >>> node = astroid.extract_node(''' - ... def my_func(arg): - ... return arg + 1 - ... ''') - >>> node - - """ - - _astroid_fields = ("decorators", "args", "returns", "body") - _multi_line_block_fields = ("body",) - returns = None - decorators = None - """The decorators that are applied to this method or function. - - :type: Decorators or None - """ - special_attributes = objectmodel.FunctionModel() - """The names of special attributes that this function has. - - :type: objectmodel.FunctionModel - """ - is_function = True - """Whether this node indicates a function. - - For a :class:`FunctionDef` this is always ``True``. - - :type: bool - """ - type_annotation = None - """If present, this will contain the type annotation passed by a type comment - - :type: NodeNG or None - """ - type_comment_args = None - """ - If present, this will contain the type annotation for arguments - passed by a type comment - """ - type_comment_returns = None - """If present, this will contain the return type annotation, passed by a type comment""" - # attributes below are set by the builder module or by raw factories - _other_fields = ("name", "doc") - _other_other_fields = ( - "locals", - "_type", - "type_comment_returns", - "type_comment_args", - ) - _type = None - - def __init__(self, name=None, doc=None, lineno=None, col_offset=None, parent=None): - """ - :param name: The name of the function. - :type name: str or None - - :param doc: The function's docstring. - :type doc: str or None - - :param lineno: The line that this node appears on in the source code. - :type lineno: int or None - - :param col_offset: The column that this node appears on in the - source code. - :type col_offset: int or None - - :param parent: The parent node in the syntax tree. - :type parent: NodeNG or None - """ - self.name = name - """The name of the function. - - :type name: str or None - """ - - self.doc = doc - """The function's docstring. - - :type doc: str or None - """ - - self.instance_attrs = {} - super().__init__(lineno, col_offset, parent) - if parent: - frame = parent.frame() - frame.set_local(name, self) - - # pylint: disable=arguments-differ; different than Lambdas - def postinit( - self, - args, - body, - decorators=None, - returns=None, - type_comment_returns=None, - type_comment_args=None, - ): - """Do some setup after initialisation. - - :param args: The arguments that the function takes. - :type args: Arguments or list - - :param body: The contents of the function body. - :type body: list(NodeNG) - - :param decorators: The decorators that are applied to this - method or function. - :type decorators: Decorators or None - :params type_comment_returns: - The return type annotation passed via a type comment. - :params type_comment_args: - The args type annotation passed via a type comment. - """ - self.args = args - self.body = body - self.decorators = decorators - self.returns = returns - self.type_comment_returns = type_comment_returns - self.type_comment_args = type_comment_args - - @decorators_mod.cachedproperty - def extra_decorators(self): - """The extra decorators that this function can have. - - Additional decorators are considered when they are used as - assignments, as in ``method = staticmethod(method)``. - The property will return all the callables that are used for - decoration. - - :type: list(NodeNG) - """ - frame = self.parent.frame() - if not isinstance(frame, ClassDef): - return [] - - decorators = [] - for assign in frame._get_assign_nodes(): - if isinstance(assign.value, node_classes.Call) and isinstance( - assign.value.func, node_classes.Name - ): - for assign_node in assign.targets: - if not isinstance(assign_node, node_classes.AssignName): - # Support only `name = callable(name)` - continue - - if assign_node.name != self.name: - # Interested only in the assignment nodes that - # decorates the current method. - continue - try: - meth = frame[self.name] - except KeyError: - continue - else: - # Must be a function and in the same frame as the - # original method. - if ( - isinstance(meth, FunctionDef) - and assign_node.frame() == frame - ): - decorators.append(assign.value) - return decorators - - @decorators_mod.cachedproperty - def type( - self - ): # pylint: disable=invalid-overridden-method,too-many-return-statements - """The function type for this node. - - Possible values are: method, function, staticmethod, classmethod. - - :type: str - """ - for decorator in self.extra_decorators: - if decorator.func.name in BUILTIN_DESCRIPTORS: - return decorator.func.name - - frame = self.parent.frame() - type_name = "function" - if isinstance(frame, ClassDef): - if self.name == "__new__": - return "classmethod" - if sys.version_info >= (3, 6) and self.name == "__init_subclass__": - return "classmethod" - - type_name = "method" - - if not self.decorators: - return type_name - - for node in self.decorators.nodes: - if isinstance(node, node_classes.Name): - if node.name in BUILTIN_DESCRIPTORS: - return node.name - if ( - isinstance(node, node_classes.Attribute) - and isinstance(node.expr, node_classes.Name) - and node.expr.name == BUILTINS - and node.attrname in BUILTIN_DESCRIPTORS - ): - return node.attrname - - if isinstance(node, node_classes.Call): - # Handle the following case: - # @some_decorator(arg1, arg2) - # def func(...) - # - try: - current = next(node.func.infer()) - except exceptions.InferenceError: - continue - _type = _infer_decorator_callchain(current) - if _type is not None: - return _type - - try: - for inferred in node.infer(): - # Check to see if this returns a static or a class method. - _type = _infer_decorator_callchain(inferred) - if _type is not None: - return _type - - if not isinstance(inferred, ClassDef): - continue - for ancestor in inferred.ancestors(): - if not isinstance(ancestor, ClassDef): - continue - if ancestor.is_subtype_of("%s.classmethod" % BUILTINS): - return "classmethod" - if ancestor.is_subtype_of("%s.staticmethod" % BUILTINS): - return "staticmethod" - except exceptions.InferenceError: - pass - return type_name - - @decorators_mod.cachedproperty - def fromlineno(self): - """The first line that this node appears on in the source code. - - :type: int or None - """ - # lineno is the line number of the first decorator, we want the def - # statement lineno - lineno = self.lineno - if self.decorators is not None: - lineno += sum( - node.tolineno - node.lineno + 1 for node in self.decorators.nodes - ) - - return lineno - - @decorators_mod.cachedproperty - def blockstart_tolineno(self): - """The line on which the beginning of this block ends. - - :type: int - """ - return self.args.tolineno - - def block_range(self, lineno): - """Get a range from the given line number to where this node ends. - - :param lineno: Unused. - :type lineno: int - - :returns: The range of line numbers that this node belongs to, - :rtype: tuple(int, int) - """ - return self.fromlineno, self.tolineno - - def getattr(self, name, context=None): - """this method doesn't look in the instance_attrs dictionary since it's - done by an Instance proxy at inference time. - """ - if not name: - raise exceptions.AttributeInferenceError( - target=self, attribute=name, context=context - ) - - found_attrs = [] - if name in self.instance_attrs: - found_attrs = self.instance_attrs[name] - if name in self.special_attributes: - found_attrs.append(self.special_attributes.lookup(name)) - if found_attrs: - return found_attrs - raise exceptions.AttributeInferenceError(target=self, attribute=name) - - def igetattr(self, name, context=None): - """Inferred getattr, which returns an iterator of inferred statements.""" - try: - return bases._infer_stmts(self.getattr(name, context), context, frame=self) - except exceptions.AttributeInferenceError as error: - raise exceptions.InferenceError( - error.message, target=self, attribute=name, context=context - ) from error - - def is_method(self): - """Check if this function node represents a method. - - :returns: True if this is a method, False otherwise. - :rtype: bool - """ - # check we are defined in a ClassDef, because this is usually expected - # (e.g. pylint...) when is_method() return True - return self.type != "function" and isinstance(self.parent.frame(), ClassDef) - - @decorators_mod.cached - def decoratornames(self, context=None): - """Get the qualified names of each of the decorators on this function. - - :param context: - An inference context that can be passed to inference functions - :returns: The names of the decorators. - :rtype: set(str) - """ - result = set() - decoratornodes = [] - if self.decorators is not None: - decoratornodes += self.decorators.nodes - decoratornodes += self.extra_decorators - for decnode in decoratornodes: - try: - for infnode in decnode.infer(context=context): - result.add(infnode.qname()) - except exceptions.InferenceError: - continue - return result - - def is_bound(self): - """Check if the function is bound to an instance or class. - - :returns: True if the function is bound to an instance or class, - False otherwise. - :rtype: bool - """ - return self.type == "classmethod" - - def is_abstract(self, pass_is_abstract=True): - """Check if the method is abstract. - - A method is considered abstract if any of the following is true: - * The only statement is 'raise NotImplementedError' - * The only statement is 'pass' and pass_is_abstract is True - * The method is annotated with abc.astractproperty/abc.abstractmethod - - :returns: True if the method is abstract, False otherwise. - :rtype: bool - """ - if self.decorators: - for node in self.decorators.nodes: - try: - inferred = next(node.infer()) - except exceptions.InferenceError: - continue - if inferred and inferred.qname() in ( - "abc.abstractproperty", - "abc.abstractmethod", - ): - return True - - for child_node in self.body: - if isinstance(child_node, node_classes.Raise): - if child_node.raises_not_implemented(): - return True - return pass_is_abstract and isinstance(child_node, node_classes.Pass) - # empty function is the same as function with a single "pass" statement - if pass_is_abstract: - return True - - def is_generator(self): - """Check if this is a generator function. - - :returns: True is this is a generator function, False otherwise. - :rtype: bool - """ - return bool(next(self._get_yield_nodes_skip_lambdas(), False)) - - def infer_call_result(self, caller=None, context=None): - """Infer what the function returns when called. - - :returns: What the function returns. - :rtype: iterable(NodeNG or Uninferable) or None - """ - if self.is_generator(): - if isinstance(self, AsyncFunctionDef): - generator_cls = bases.AsyncGenerator - else: - generator_cls = bases.Generator - result = generator_cls(self) - yield result - return - # This is really a gigantic hack to work around metaclass generators - # that return transient class-generating functions. Pylint's AST structure - # cannot handle a base class object that is only used for calling __new__, - # but does not contribute to the inheritance structure itself. We inject - # a fake class into the hierarchy here for several well-known metaclass - # generators, and filter it out later. - if ( - self.name == "with_metaclass" - and len(self.args.args) == 1 - and self.args.vararg is not None - ): - metaclass = next(caller.args[0].infer(context)) - if isinstance(metaclass, ClassDef): - class_bases = [next(arg.infer(context)) for arg in caller.args[1:]] - new_class = ClassDef(name="temporary_class") - new_class.hide = True - new_class.parent = self - new_class.postinit( - bases=[base for base in class_bases if base != util.Uninferable], - body=[], - decorators=[], - metaclass=metaclass, - ) - yield new_class - return - returns = self._get_return_nodes_skip_functions() - - first_return = next(returns, None) - if not first_return: - if self.body and isinstance(self.body[-1], node_classes.Assert): - yield node_classes.Const(None) - return - - raise exceptions.InferenceError( - "The function does not have any return statements" - ) - - for returnnode in itertools.chain((first_return,), returns): - if returnnode.value is None: - yield node_classes.Const(None) - else: - try: - yield from returnnode.value.infer(context) - except exceptions.InferenceError: - yield util.Uninferable - - def bool_value(self, context=None): - """Determine the boolean value of this node. - - :returns: The boolean value of this node. - For a :class:`FunctionDef` this is always ``True``. - :rtype: bool - """ - return True - - def get_children(self): - if self.decorators is not None: - yield self.decorators - - yield self.args - - if self.returns is not None: - yield self.returns - - yield from self.body - - def scope_lookup(self, node, name, offset=0): - """Lookup where the given name is assigned.""" - if name == "__class__": - # __class__ is an implicit closure reference created by the compiler - # if any methods in a class body refer to either __class__ or super. - # In our case, we want to be able to look it up in the current scope - # when `__class__` is being used. - frame = self.parent.frame() - if isinstance(frame, ClassDef): - return self, [frame] - return super().scope_lookup(node, name, offset) - - -class AsyncFunctionDef(FunctionDef): - """Class representing an :class:`ast.FunctionDef` node. - - A :class:`AsyncFunctionDef` is an asynchronous function - created with the `async` keyword. - - >>> node = astroid.extract_node(''' - async def func(things): - async for thing in things: - print(thing) - ''') - >>> node - - >>> node.body[0] - - """ - - -def _rec_get_names(args, names=None): - """return a list of all argument names""" - if names is None: - names = [] - for arg in args: - if isinstance(arg, node_classes.Tuple): - _rec_get_names(arg.elts, names) - else: - names.append(arg.name) - return names - - -def _is_metaclass(klass, seen=None): - """ Return if the given class can be - used as a metaclass. - """ - if klass.name == "type": - return True - if seen is None: - seen = set() - for base in klass.bases: - try: - for baseobj in base.infer(): - baseobj_name = baseobj.qname() - if baseobj_name in seen: - continue - - seen.add(baseobj_name) - if isinstance(baseobj, bases.Instance): - # not abstract - return False - if baseobj is util.Uninferable: - continue - if baseobj is klass: - continue - if not isinstance(baseobj, ClassDef): - continue - if baseobj._type == "metaclass": - return True - if _is_metaclass(baseobj, seen): - return True - except exceptions.InferenceError: - continue - return False - - -def _class_type(klass, ancestors=None): - """return a ClassDef node type to differ metaclass and exception - from 'regular' classes - """ - # XXX we have to store ancestors in case we have an ancestor loop - if klass._type is not None: - return klass._type - if _is_metaclass(klass): - klass._type = "metaclass" - elif klass.name.endswith("Exception"): - klass._type = "exception" - else: - if ancestors is None: - ancestors = set() - klass_name = klass.qname() - if klass_name in ancestors: - # XXX we are in loop ancestors, and have found no type - klass._type = "class" - return "class" - ancestors.add(klass_name) - for base in klass.ancestors(recurs=False): - name = _class_type(base, ancestors) - if name != "class": - if name == "metaclass" and not _is_metaclass(klass): - # don't propagate it if the current class - # can't be a metaclass - continue - klass._type = base.type - break - if klass._type is None: - klass._type = "class" - return klass._type - - -def get_wrapping_class(node): - """Get the class that wraps the given node. - - We consider that a class wraps a node if the class - is a parent for the said node. - - :returns: The class that wraps the given node - :rtype: ClassDef or None - """ - - klass = node.frame() - while klass is not None and not isinstance(klass, ClassDef): - if klass.parent is None: - klass = None - else: - klass = klass.parent.frame() - return klass - - -class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG, node_classes.Statement): - """Class representing an :class:`ast.ClassDef` node. - - >>> node = astroid.extract_node(''' - class Thing: - def my_meth(self, arg): - return arg + self.offset - ''') - >>> node - - """ - - # some of the attributes below are set by the builder module or - # by a raw factories - - # a dictionary of class instances attributes - _astroid_fields = ("decorators", "bases", "body") # name - - decorators = None - """The decorators that are applied to this class. - - :type: Decorators or None - """ - special_attributes = objectmodel.ClassModel() - """The names of special attributes that this class has. - - :type: objectmodel.ClassModel - """ - - _type = None - _metaclass_hack = False - hide = False - type = property( - _class_type, - doc=( - "The class type for this node.\n\n" - "Possible values are: class, metaclass, exception.\n\n" - ":type: str" - ), - ) - _other_fields = ("name", "doc") - _other_other_fields = ("locals", "_newstyle") - _newstyle = None - - def __init__(self, name=None, doc=None, lineno=None, col_offset=None, parent=None): - """ - :param name: The name of the class. - :type name: str or None - - :param doc: The function's docstring. - :type doc: str or None - - :param lineno: The line that this node appears on in the source code. - :type lineno: int or None - - :param col_offset: The column that this node appears on in the - source code. - :type col_offset: int or None - - :param parent: The parent node in the syntax tree. - :type parent: NodeNG or None - """ - self.instance_attrs = {} - self.locals = {} - """A map of the name of a local variable to the node defining it. - - :type: dict(str, NodeNG) - """ - - self.keywords = [] - """The keywords given to the class definition. - - This is usually for :pep:`3115` style metaclass declaration. - - :type: list(Keyword) or None - """ - - self.bases = [] - """What the class inherits from. - - :type: list(NodeNG) - """ - - self.body = [] - """The contents of the class body. - - :type: list(NodeNG) - """ - - self.name = name - """The name of the class. - - :type name: str or None - """ - - self.doc = doc - """The class' docstring. - - :type doc: str or None - """ - - super().__init__(lineno, col_offset, parent) - if parent is not None: - parent.frame().set_local(name, self) - - for local_name, node in self.implicit_locals(): - self.add_local_node(node, local_name) - - def implicit_parameters(self): - return 1 - - def implicit_locals(self): - """Get implicitly defined class definition locals. - - :returns: the the name and Const pair for each local - :rtype: tuple(tuple(str, node_classes.Const), ...) - """ - locals_ = (("__module__", self.special_attributes.attr___module__),) - # __qualname__ is defined in PEP3155 - locals_ += (("__qualname__", self.special_attributes.attr___qualname__),) - return locals_ - - # pylint: disable=redefined-outer-name - def postinit( - self, bases, body, decorators, newstyle=None, metaclass=None, keywords=None - ): - """Do some setup after initialisation. - - :param bases: What the class inherits from. - :type bases: list(NodeNG) - - :param body: The contents of the class body. - :type body: list(NodeNG) - - :param decorators: The decorators that are applied to this class. - :type decorators: Decorators or None - - :param newstyle: Whether this is a new style class or not. - :type newstyle: bool or None - - :param metaclass: The metaclass of this class. - :type metaclass: NodeNG or None - - :param keywords: The keywords given to the class definition. - :type keywords: list(Keyword) or None - """ - self.keywords = keywords - self.bases = bases - self.body = body - self.decorators = decorators - if newstyle is not None: - self._newstyle = newstyle - if metaclass is not None: - self._metaclass = metaclass - - def _newstyle_impl(self, context=None): - if context is None: - context = contextmod.InferenceContext() - if self._newstyle is not None: - return self._newstyle - for base in self.ancestors(recurs=False, context=context): - if base._newstyle_impl(context): - self._newstyle = True - break - klass = self.declared_metaclass() - # could be any callable, we'd need to infer the result of klass(name, - # bases, dict). punt if it's not a class node. - if klass is not None and isinstance(klass, ClassDef): - self._newstyle = klass._newstyle_impl(context) - if self._newstyle is None: - self._newstyle = False - return self._newstyle - - _newstyle = None - newstyle = property( - _newstyle_impl, - doc=("Whether this is a new style class or not\n\n" ":type: bool or None"), - ) - - @decorators_mod.cachedproperty - def blockstart_tolineno(self): - """The line on which the beginning of this block ends. - - :type: int - """ - if self.bases: - return self.bases[-1].tolineno - - return self.fromlineno - - def block_range(self, lineno): - """Get a range from the given line number to where this node ends. - - :param lineno: Unused. - :type lineno: int - - :returns: The range of line numbers that this node belongs to, - :rtype: tuple(int, int) - """ - return self.fromlineno, self.tolineno - - def pytype(self): - """Get the name of the type that this node represents. - - :returns: The name of the type. - :rtype: str - """ - if self.newstyle: - return "%s.type" % BUILTINS - return "%s.classobj" % BUILTINS - - def display_type(self): - """A human readable type of this node. - - :returns: The type of this node. - :rtype: str - """ - return "Class" - - def callable(self): - """Whether this node defines something that is callable. - - :returns: True if this defines something that is callable, - False otherwise. - For a :class:`ClassDef` this is always ``True``. - :rtype: bool - """ - return True - - def is_subtype_of(self, type_name, context=None): - """Whether this class is a subtype of the given type. - - :param type_name: The name of the type of check against. - :type type_name: str - - :returns: True if this class is a subtype of the given type, - False otherwise. - :rtype: bool - """ - if self.qname() == type_name: - return True - for anc in self.ancestors(context=context): - if anc.qname() == type_name: - return True - return False - - def _infer_type_call(self, caller, context): - name_node = next(caller.args[0].infer(context)) - if isinstance(name_node, node_classes.Const) and isinstance( - name_node.value, str - ): - name = name_node.value - else: - return util.Uninferable - - result = ClassDef(name, None) - - # Get the bases of the class. - class_bases = next(caller.args[1].infer(context)) - if isinstance(class_bases, (node_classes.Tuple, node_classes.List)): - bases = [] - for base in class_bases.itered(): - inferred = next(base.infer(context=context)) - if inferred: - bases.append( - node_classes.EvaluatedObject(original=base, value=inferred) - ) - result.bases = bases - else: - # There is currently no AST node that can represent an 'unknown' - # node (Uninferable is not an AST node), therefore we simply return Uninferable here - # although we know at least the name of the class. - return util.Uninferable - - # Get the members of the class - try: - members = next(caller.args[2].infer(context)) - except exceptions.InferenceError: - members = None - - if members and isinstance(members, node_classes.Dict): - for attr, value in members.items: - if isinstance(attr, node_classes.Const) and isinstance(attr.value, str): - result.locals[attr.value] = [value] - - result.parent = caller.parent - return result - - def infer_call_result(self, caller, context=None): - """infer what a class is returning when called""" - if ( - self.is_subtype_of("%s.type" % (BUILTINS,), context) - and len(caller.args) == 3 - ): - result = self._infer_type_call(caller, context) - yield result - return - - dunder_call = None - try: - metaclass = self.metaclass(context=context) - if metaclass is not None: - dunder_call = next(metaclass.igetattr("__call__", context)) - except exceptions.AttributeInferenceError: - pass - - if dunder_call and dunder_call.qname() != "builtins.type.__call__": - # Call type.__call__ if not set metaclass - # (since type is the default metaclass) - context = contextmod.bind_context_to_node(context, self) - yield from dunder_call.infer_call_result(caller, context) - else: - yield self.instantiate_class() - - def scope_lookup(self, node, name, offset=0): - """Lookup where the given name is assigned. - - :param node: The node to look for assignments up to. - Any assignments after the given node are ignored. - :type node: NodeNG - - :param name: The name to find assignments for. - :type name: str - - :param offset: The line offset to filter statements up to. - :type offset: int - - :returns: This scope node and the list of assignments associated to the - given name according to the scope where it has been found (locals, - globals or builtin). - :rtype: tuple(str, list(NodeNG)) - """ - # If the name looks like a builtin name, just try to look - # into the upper scope of this class. We might have a - # decorator that it's poorly named after a builtin object - # inside this class. - lookup_upper_frame = ( - isinstance(node.parent, node_classes.Decorators) - and name in MANAGER.builtins_module - ) - if ( - any(node == base or base.parent_of(node) for base in self.bases) - or lookup_upper_frame - ): - # Handle the case where we have either a name - # in the bases of a class, which exists before - # the actual definition or the case where we have - # a Getattr node, with that name. - # - # name = ... - # class A(name): - # def name(self): ... - # - # import name - # class A(name.Name): - # def name(self): ... - - frame = self.parent.frame() - # line offset to avoid that class A(A) resolve the ancestor to - # the defined class - offset = -1 - else: - frame = self - return frame._scope_lookup(node, name, offset) - - @property - def basenames(self): - """The names of the parent classes - - Names are given in the order they appear in the class definition. - - :type: list(str) - """ - return [bnode.as_string() for bnode in self.bases] - - def ancestors(self, recurs=True, context=None): - """Iterate over the base classes in prefixed depth first order. - - :param recurs: Whether to recurse or return direct ancestors only. - :type recurs: bool - - :returns: The base classes - :rtype: iterable(NodeNG) - """ - # FIXME: should be possible to choose the resolution order - # FIXME: inference make infinite loops possible here - yielded = {self} - if context is None: - context = contextmod.InferenceContext() - if not self.bases and self.qname() != "builtins.object": - yield builtin_lookup("object")[1][0] - return - - for stmt in self.bases: - with context.restore_path(): - try: - for baseobj in stmt.infer(context): - if not isinstance(baseobj, ClassDef): - if isinstance(baseobj, bases.Instance): - baseobj = baseobj._proxied - else: - continue - if not baseobj.hide: - if baseobj in yielded: - continue - yielded.add(baseobj) - yield baseobj - if not recurs: - continue - for grandpa in baseobj.ancestors(recurs=True, context=context): - if grandpa is self: - # This class is the ancestor of itself. - break - if grandpa in yielded: - continue - yielded.add(grandpa) - yield grandpa - except exceptions.InferenceError: - continue - - def local_attr_ancestors(self, name, context=None): - """Iterate over the parents that define the given name. - - :param name: The name to find definitions for. - :type name: str - - :returns: The parents that define the given name. - :rtype: iterable(NodeNG) - """ - # Look up in the mro if we can. This will result in the - # attribute being looked up just as Python does it. - try: - ancestors = self.mro(context)[1:] - except exceptions.MroError: - # Fallback to use ancestors, we can't determine - # a sane MRO. - ancestors = self.ancestors(context=context) - for astroid in ancestors: - if name in astroid: - yield astroid - - def instance_attr_ancestors(self, name, context=None): - """Iterate over the parents that define the given name as an attribute. - - :param name: The name to find definitions for. - :type name: str - - :returns: The parents that define the given name as - an instance attribute. - :rtype: iterable(NodeNG) - """ - for astroid in self.ancestors(context=context): - if name in astroid.instance_attrs: - yield astroid - - def has_base(self, node): - """Whether this class directly inherits from the given node. - - :param node: The node to check for. - :type node: NodeNG - - :returns: True if this class directly inherits from the given node. - :rtype: bool - """ - return node in self.bases - - def local_attr(self, name, context=None): - """Get the list of assign nodes associated to the given name. - - Assignments are looked for in both this class and in parents. - - :returns: The list of assignments to the given name. - :rtype: list(NodeNG) - - :raises AttributeInferenceError: If no attribute with this name - can be found in this class or parent classes. - """ - result = [] - if name in self.locals: - result = self.locals[name] - else: - class_node = next(self.local_attr_ancestors(name, context), None) - if class_node: - result = class_node.locals[name] - result = [n for n in result if not isinstance(n, node_classes.DelAttr)] - if result: - return result - raise exceptions.AttributeInferenceError( - target=self, attribute=name, context=context - ) - - def instance_attr(self, name, context=None): - """Get the list of nodes associated to the given attribute name. - - Assignments are looked for in both this class and in parents. - - :returns: The list of assignments to the given name. - :rtype: list(NodeNG) - - :raises AttributeInferenceError: If no attribute with this name - can be found in this class or parent classes. - """ - # Return a copy, so we don't modify self.instance_attrs, - # which could lead to infinite loop. - values = list(self.instance_attrs.get(name, [])) - # get all values from parents - for class_node in self.instance_attr_ancestors(name, context): - values += class_node.instance_attrs[name] - values = [n for n in values if not isinstance(n, node_classes.DelAttr)] - if values: - return values - raise exceptions.AttributeInferenceError( - target=self, attribute=name, context=context - ) - - def instantiate_class(self): - """Get an :class:`Instance` of the :class:`ClassDef` node. - - :returns: An :class:`Instance` of the :class:`ClassDef` node, - or self if this is not possible. - :rtype: Instance or ClassDef - """ - try: - if any(cls.name in EXCEPTION_BASE_CLASSES for cls in self.mro()): - # Subclasses of exceptions can be exception instances - return objects.ExceptionInstance(self) - except exceptions.MroError: - pass - return bases.Instance(self) - - def getattr(self, name, context=None, class_context=True): - """Get an attribute from this class, using Python's attribute semantic. - - This method doesn't look in the :attr:`instance_attrs` dictionary - since it is done by an :class:`Instance` proxy at inference time. - It may return an :class:`Uninferable` object if - the attribute has not been - found, but a ``__getattr__`` or ``__getattribute__`` method is defined. - If ``class_context`` is given, then it is considered that the - attribute is accessed from a class context, - e.g. ClassDef.attribute, otherwise it might have been accessed - from an instance as well. If ``class_context`` is used in that - case, then a lookup in the implicit metaclass and the explicit - metaclass will be done. - - :param name: The attribute to look for. - :type name: str - - :param class_context: Whether the attribute can be accessed statically. - :type class_context: bool - - :returns: The attribute. - :rtype: list(NodeNG) - - :raises AttributeInferenceError: If the attribute cannot be inferred. - """ - if not name: - raise exceptions.AttributeInferenceError( - target=self, attribute=name, context=context - ) - - values = self.locals.get(name, []) - if name in self.special_attributes and class_context and not values: - result = [self.special_attributes.lookup(name)] - if name == "__bases__": - # Need special treatment, since they are mutable - # and we need to return all the values. - result += values - return result - - # don't modify the list in self.locals! - values = list(values) - for classnode in self.ancestors(recurs=True, context=context): - values += classnode.locals.get(name, []) - - if class_context: - values += self._metaclass_lookup_attribute(name, context) - - if not values: - raise exceptions.AttributeInferenceError( - target=self, attribute=name, context=context - ) - - # Look for AnnAssigns, which are not attributes in the purest sense. - for value in values: - if isinstance(value, node_classes.AssignName): - stmt = value.statement() - if isinstance(stmt, node_classes.AnnAssign) and stmt.value is None: - raise exceptions.AttributeInferenceError( - target=self, attribute=name, context=context - ) - return values - - def _metaclass_lookup_attribute(self, name, context): - """Search the given name in the implicit and the explicit metaclass.""" - attrs = set() - implicit_meta = self.implicit_metaclass() - context = contextmod.copy_context(context) - metaclass = self.metaclass(context=context) - for cls in {implicit_meta, metaclass}: - if cls and cls != self and isinstance(cls, ClassDef): - cls_attributes = self._get_attribute_from_metaclass(cls, name, context) - attrs.update(set(cls_attributes)) - return attrs - - def _get_attribute_from_metaclass(self, cls, name, context): - try: - attrs = cls.getattr(name, context=context, class_context=True) - except exceptions.AttributeInferenceError: - return - - for attr in bases._infer_stmts(attrs, context, frame=cls): - if not isinstance(attr, FunctionDef): - yield attr - continue - - if isinstance(attr, objects.Property): - yield attr - continue - if attr.type == "classmethod": - # If the method is a classmethod, then it will - # be bound to the metaclass, not to the class - # from where the attribute is retrieved. - # get_wrapping_class could return None, so just - # default to the current class. - frame = get_wrapping_class(attr) or self - yield bases.BoundMethod(attr, frame) - elif attr.type == "staticmethod": - yield attr - else: - yield bases.BoundMethod(attr, self) - - def igetattr(self, name, context=None, class_context=True): - """Infer the possible values of the given variable. - - :param name: The name of the variable to infer. - :type name: str - - :returns: The inferred possible values. - :rtype: iterable(NodeNG or Uninferable) - """ - # set lookup name since this is necessary to infer on import nodes for - # instance - context = contextmod.copy_context(context) - context.lookupname = name - - metaclass = self.declared_metaclass(context=context) - try: - attributes = self.getattr(name, context, class_context=class_context) - # If we have more than one attribute, make sure that those starting from - # the second one are from the same scope. This is to account for modifications - # to the attribute happening *after* the attribute's definition (e.g. AugAssigns on lists) - if len(attributes) > 1: - first_attr, attributes = attributes[0], attributes[1:] - first_scope = first_attr.scope() - attributes = [first_attr] + [ - attr - for attr in attributes - if attr.parent and attr.parent.scope() == first_scope - ] - - for inferred in bases._infer_stmts(attributes, context, frame=self): - # yield Uninferable object instead of descriptors when necessary - if not isinstance(inferred, node_classes.Const) and isinstance( - inferred, bases.Instance - ): - try: - inferred._proxied.getattr("__get__", context) - except exceptions.AttributeInferenceError: - yield inferred - else: - yield util.Uninferable - elif isinstance(inferred, objects.Property): - function = inferred.function - if not class_context: - # Through an instance so we can solve the property - yield from function.infer_call_result( - caller=self, context=context - ) - # If we have a metaclass, we're accessing this attribute through - # the class itself, which means we can solve the property - elif metaclass: - # Resolve a property as long as it is not accessed through - # the class itself. - yield from function.infer_call_result( - caller=self, context=context - ) - else: - yield inferred - else: - yield function_to_method(inferred, self) - except exceptions.AttributeInferenceError as error: - if not name.startswith("__") and self.has_dynamic_getattr(context): - # class handle some dynamic attributes, return a Uninferable object - yield util.Uninferable - else: - raise exceptions.InferenceError( - error.message, target=self, attribute=name, context=context - ) - - def has_dynamic_getattr(self, context=None): - """Check if the class has a custom __getattr__ or __getattribute__. - - If any such method is found and it is not from - builtins, nor from an extension module, then the function - will return True. - - :returns: True if the class has a custom - __getattr__ or __getattribute__, False otherwise. - :rtype: bool - """ - - def _valid_getattr(node): - root = node.root() - return root.name != BUILTINS and getattr(root, "pure_python", None) - - try: - return _valid_getattr(self.getattr("__getattr__", context)[0]) - except exceptions.AttributeInferenceError: - # if self.newstyle: XXX cause an infinite recursion error - try: - getattribute = self.getattr("__getattribute__", context)[0] - return _valid_getattr(getattribute) - except exceptions.AttributeInferenceError: - pass - return False - - def getitem(self, index, context=None): - """Return the inference of a subscript. - - This is basically looking up the method in the metaclass and calling it. - - :returns: The inferred value of a subscript to this class. - :rtype: NodeNG - - :raises AstroidTypeError: If this class does not define a - ``__getitem__`` method. - """ - try: - methods = dunder_lookup.lookup(self, "__getitem__") - except exceptions.AttributeInferenceError as exc: - raise exceptions.AstroidTypeError(node=self, context=context) from exc - - method = methods[0] - - # Create a new callcontext for providing index as an argument. - new_context = contextmod.bind_context_to_node(context, self) - new_context.callcontext = contextmod.CallContext(args=[index]) - - try: - return next(method.infer_call_result(self, new_context)) - except exceptions.InferenceError: - return util.Uninferable - - def methods(self): - """Iterate over all of the method defined in this class and its parents. - - :returns: The methods defined on the class. - :rtype: iterable(FunctionDef) - """ - done = {} - for astroid in itertools.chain(iter((self,)), self.ancestors()): - for meth in astroid.mymethods(): - if meth.name in done: - continue - done[meth.name] = None - yield meth - - def mymethods(self): - """Iterate over all of the method defined in this class only. - - :returns: The methods defined on the class. - :rtype: iterable(FunctionDef) - """ - for member in self.values(): - if isinstance(member, FunctionDef): - yield member - - def implicit_metaclass(self): - """Get the implicit metaclass of the current class. - - For newstyle classes, this will return an instance of builtins.type. - For oldstyle classes, it will simply return None, since there's - no implicit metaclass there. - - :returns: The metaclass. - :rtype: builtins.type or None - """ - if self.newstyle: - return builtin_lookup("type")[1][0] - return None - - _metaclass = None - - def declared_metaclass(self, context=None): - """Return the explicit declared metaclass for the current class. - - An explicit declared metaclass is defined - either by passing the ``metaclass`` keyword argument - in the class definition line (Python 3) or (Python 2) by - having a ``__metaclass__`` class attribute, or if there are - no explicit bases but there is a global ``__metaclass__`` variable. - - :returns: The metaclass of this class, - or None if one could not be found. - :rtype: NodeNG or None - """ - for base in self.bases: - try: - for baseobj in base.infer(context=context): - if isinstance(baseobj, ClassDef) and baseobj.hide: - self._metaclass = baseobj._metaclass - self._metaclass_hack = True - break - except exceptions.InferenceError: - pass - - if self._metaclass: - # Expects this from Py3k TreeRebuilder - try: - return next( - node - for node in self._metaclass.infer(context=context) - if node is not util.Uninferable - ) - except (exceptions.InferenceError, StopIteration): - return None - - return None - - def _find_metaclass(self, seen=None, context=None): - if seen is None: - seen = set() - seen.add(self) - - klass = self.declared_metaclass(context=context) - if klass is None: - for parent in self.ancestors(context=context): - if parent not in seen: - klass = parent._find_metaclass(seen) - if klass is not None: - break - return klass - - def metaclass(self, context=None): - """Get the metaclass of this class. - - If this class does not define explicitly a metaclass, - then the first defined metaclass in ancestors will be used - instead. - - :returns: The metaclass of this class. - :rtype: NodeNG or None - """ - return self._find_metaclass(context=context) - - def has_metaclass_hack(self): - return self._metaclass_hack - - def _islots(self): - """ Return an iterator with the inferred slots. """ - if "__slots__" not in self.locals: - return None - for slots in self.igetattr("__slots__"): - # check if __slots__ is a valid type - for meth in ITER_METHODS: - try: - slots.getattr(meth) - break - except exceptions.AttributeInferenceError: - continue - else: - continue - - if isinstance(slots, node_classes.Const): - # a string. Ignore the following checks, - # but yield the node, only if it has a value - if slots.value: - yield slots - continue - if not hasattr(slots, "itered"): - # we can't obtain the values, maybe a .deque? - continue - - if isinstance(slots, node_classes.Dict): - values = [item[0] for item in slots.items] - else: - values = slots.itered() - if values is util.Uninferable: - continue - if not values: - # Stop the iteration, because the class - # has an empty list of slots. - return values - - for elt in values: - try: - for inferred in elt.infer(): - if inferred is util.Uninferable: - continue - if not isinstance( - inferred, node_classes.Const - ) or not isinstance(inferred.value, str): - continue - if not inferred.value: - continue - yield inferred - except exceptions.InferenceError: - continue - - return None - - def _slots(self): - if not self.newstyle: - raise NotImplementedError( - "The concept of slots is undefined for old-style classes." - ) - - slots = self._islots() - try: - first = next(slots) - except StopIteration as exc: - # The class doesn't have a __slots__ definition or empty slots. - if exc.args and exc.args[0] not in ("", None): - return exc.args[0] - return None - return [first] + list(slots) - - # Cached, because inferring them all the time is expensive - @decorators_mod.cached - def slots(self): - """Get all the slots for this node. - - :returns: The names of slots for this class. - If the class doesn't define any slot, through the ``__slots__`` - variable, then this function will return a None. - Also, it will return None in the case the slots were not inferred. - :rtype: list(str) or None - """ - - def grouped_slots(): - # Not interested in object, since it can't have slots. - for cls in self.mro()[:-1]: - try: - cls_slots = cls._slots() - except NotImplementedError: - continue - if cls_slots is not None: - yield from cls_slots - else: - yield None - - if not self.newstyle: - raise NotImplementedError( - "The concept of slots is undefined for old-style classes." - ) - - slots = list(grouped_slots()) - if not all(slot is not None for slot in slots): - return None - - return sorted(set(slots), key=lambda item: item.value) - - def _inferred_bases(self, context=None): - # Similar with .ancestors, but the difference is when one base is inferred, - # only the first object is wanted. That's because - # we aren't interested in superclasses, as in the following - # example: - # - # class SomeSuperClass(object): pass - # class SomeClass(SomeSuperClass): pass - # class Test(SomeClass): pass - # - # Inferring SomeClass from the Test's bases will give - # us both SomeClass and SomeSuperClass, but we are interested - # only in SomeClass. - - if context is None: - context = contextmod.InferenceContext() - if not self.bases and self.qname() != "builtins.object": - yield builtin_lookup("object")[1][0] - return - - for stmt in self.bases: - try: - baseobj = next(stmt.infer(context=context)) - except exceptions.InferenceError: - continue - if isinstance(baseobj, bases.Instance): - baseobj = baseobj._proxied - if not isinstance(baseobj, ClassDef): - continue - if not baseobj.hide: - yield baseobj - else: - yield from baseobj.bases - - def _compute_mro(self, context=None): - inferred_bases = list(self._inferred_bases(context=context)) - bases_mro = [] - for base in inferred_bases: - if base is self: - continue - - try: - mro = base._compute_mro(context=context) - bases_mro.append(mro) - except NotImplementedError: - # Some classes have in their ancestors both newstyle and - # old style classes. For these we can't retrieve the .mro, - # although in Python it's possible, since the class we are - # currently working is in fact new style. - # So, we fallback to ancestors here. - ancestors = list(base.ancestors(context=context)) - bases_mro.append(ancestors) - - unmerged_mro = [[self]] + bases_mro + [inferred_bases] - unmerged_mro = list(clean_duplicates_mro(unmerged_mro, self, context)) - return _c3_merge(unmerged_mro, self, context) - - def mro(self, context=None) -> List["ClassDef"]: - """Get the method resolution order, using C3 linearization. - - :returns: The list of ancestors, sorted by the mro. - :rtype: list(NodeNG) - :raises DuplicateBasesError: Duplicate bases in the same class base - :raises InconsistentMroError: A class' MRO is inconsistent - """ - return self._compute_mro(context=context) - - def bool_value(self, context=None): - """Determine the boolean value of this node. - - :returns: The boolean value of this node. - For a :class:`ClassDef` this is always ``True``. - :rtype: bool - """ - return True - - def get_children(self): - if self.decorators is not None: - yield self.decorators - - yield from self.bases - yield from self.body - - @decorators_mod.cached - def _get_assign_nodes(self): - children_assign_nodes = ( - child_node._get_assign_nodes() for child_node in self.body - ) - return list(itertools.chain.from_iterable(children_assign_nodes)) diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/test_utils.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/test_utils.py deleted file mode 100644 index e22c7a4..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/test_utils.py +++ /dev/null @@ -1,73 +0,0 @@ -# Copyright (c) 2013-2014 Google, Inc. -# Copyright (c) 2014 LOGILAB S.A. (Paris, FRANCE) -# Copyright (c) 2015-2016, 2018-2019 Claudiu Popa -# Copyright (c) 2015-2016 Ceridwen -# Copyright (c) 2016 Jakub Wilk -# Copyright (c) 2018 Anthony Sottile - -# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html -# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER - -"""Utility functions for test code that uses astroid ASTs as input.""" -import contextlib -import functools -import sys -import warnings - -import pytest - -from astroid import nodes - - -def require_version(minver=None, maxver=None): - """ Compare version of python interpreter to the given one. Skip the test - if older. - """ - - def parse(string, default=None): - string = string or default - try: - return tuple(int(v) for v in string.split(".")) - except ValueError as exc: - raise ValueError( - "{string} is not a correct version : should be X.Y[.Z].".format( - string=string - ) - ) from exc - - def check_require_version(f): - current = sys.version_info[:3] - if parse(minver, "0") < current <= parse(maxver, "4"): - return f - - str_version = ".".join(str(v) for v in sys.version_info) - - @functools.wraps(f) - def new_f(*args, **kwargs): - if minver is not None: - pytest.skip( - "Needs Python > %s. Current version is %s." % (minver, str_version) - ) - elif maxver is not None: - pytest.skip( - "Needs Python <= %s. Current version is %s." % (maxver, str_version) - ) - - return new_f - - return check_require_version - - -def get_name_node(start_from, name, index=0): - return [n for n in start_from.nodes_of_class(nodes.Name) if n.name == name][index] - - -@contextlib.contextmanager -def enable_warning(warning): - warnings.simplefilter("always", warning) - try: - yield - finally: - # Reset it to default value, so it will take - # into account the values from the -W flag. - warnings.simplefilter("default", warning) diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/transforms.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/transforms.py deleted file mode 100644 index e5506cc..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/transforms.py +++ /dev/null @@ -1,90 +0,0 @@ -# Copyright (c) 2015-2016, 2018 Claudiu Popa -# Copyright (c) 2016 Ceridwen -# Copyright (c) 2018 Nick Drozd - -# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html -# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER - - -import collections -from functools import lru_cache - - -class TransformVisitor: - """A visitor for handling transforms. - - The standard approach of using it is to call - :meth:`~visit` with an *astroid* module and the class - will take care of the rest, walking the tree and running the - transforms for each encountered node. - """ - - TRANSFORM_MAX_CACHE_SIZE = 10000 - - def __init__(self): - self.transforms = collections.defaultdict(list) - - @lru_cache(maxsize=TRANSFORM_MAX_CACHE_SIZE) - def _transform(self, node): - """Call matching transforms for the given node if any and return the - transformed node. - """ - cls = node.__class__ - if cls not in self.transforms: - # no transform registered for this class of node - return node - - transforms = self.transforms[cls] - for transform_func, predicate in transforms: - if predicate is None or predicate(node): - ret = transform_func(node) - # if the transformation function returns something, it's - # expected to be a replacement for the node - if ret is not None: - node = ret - if ret.__class__ != cls: - # Can no longer apply the rest of the transforms. - break - return node - - def _visit(self, node): - if hasattr(node, "_astroid_fields"): - for name in node._astroid_fields: - value = getattr(node, name) - visited = self._visit_generic(value) - if visited != value: - setattr(node, name, visited) - return self._transform(node) - - def _visit_generic(self, node): - if isinstance(node, list): - return [self._visit_generic(child) for child in node] - if isinstance(node, tuple): - return tuple(self._visit_generic(child) for child in node) - if not node or isinstance(node, str): - return node - - return self._visit(node) - - def register_transform(self, node_class, transform, predicate=None): - """Register `transform(node)` function to be applied on the given - astroid's `node_class` if `predicate` is None or returns true - when called with the node as argument. - - The transform function may return a value which is then used to - substitute the original node in the tree. - """ - self.transforms[node_class].append((transform, predicate)) - - def unregister_transform(self, node_class, transform, predicate=None): - """Unregister the given transform.""" - self.transforms[node_class].remove((transform, predicate)) - - def visit(self, module): - """Walk the given astroid *tree* and transform each encountered node - - Only the nodes which have transforms registered will actually - be replaced or changed. - """ - module.body = [self._visit(child) for child in module.body] - return self._transform(module) diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/util.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/util.py deleted file mode 100644 index 3ab7561..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/astroid/util.py +++ /dev/null @@ -1,164 +0,0 @@ -# Copyright (c) 2015-2018 Claudiu Popa -# Copyright (c) 2015-2016 Ceridwen -# Copyright (c) 2018 Bryce Guinta -# Copyright (c) 2018 Nick Drozd - -# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html -# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER - -import warnings -from itertools import islice - -import importlib -import lazy_object_proxy - - -def lazy_descriptor(obj): - class DescriptorProxy(lazy_object_proxy.Proxy): - def __get__(self, instance, owner=None): - return self.__class__.__get__(self, instance) - - return DescriptorProxy(obj) - - -def lazy_import(module_name): - return lazy_object_proxy.Proxy( - lambda: importlib.import_module("." + module_name, "astroid") - ) - - -@object.__new__ -class Uninferable: - """Special inference object, which is returned when inference fails.""" - - def __repr__(self): - return "Uninferable" - - __str__ = __repr__ - - def __getattribute__(self, name): - if name == "next": - raise AttributeError("next method should not be called") - if name.startswith("__") and name.endswith("__"): - return object.__getattribute__(self, name) - if name == "accept": - return object.__getattribute__(self, name) - return self - - def __call__(self, *args, **kwargs): - return self - - def __bool__(self): - return False - - __nonzero__ = __bool__ - - def accept(self, visitor): - func = getattr(visitor, "visit_uninferable") - return func(self) - - -class BadOperationMessage: - """Object which describes a TypeError occurred somewhere in the inference chain - - This is not an exception, but a container object which holds the types and - the error which occurred. - """ - - -class BadUnaryOperationMessage(BadOperationMessage): - """Object which describes operational failures on UnaryOps.""" - - def __init__(self, operand, op, error): - self.operand = operand - self.op = op - self.error = error - - @property - def _object_type_helper(self): - helpers = lazy_import("helpers") - return helpers.object_type - - def _object_type(self, obj): - # pylint: disable=not-callable; can't infer lazy_import - objtype = self._object_type_helper(obj) - if objtype is Uninferable: - return None - - return objtype - - def __str__(self): - if hasattr(self.operand, "name"): - operand_type = self.operand.name - else: - object_type = self._object_type(self.operand) - if hasattr(object_type, "name"): - operand_type = object_type.name - else: - # Just fallback to as_string - operand_type = object_type.as_string() - - msg = "bad operand type for unary {}: {}" - return msg.format(self.op, operand_type) - - -class BadBinaryOperationMessage(BadOperationMessage): - """Object which describes type errors for BinOps.""" - - def __init__(self, left_type, op, right_type): - self.left_type = left_type - self.right_type = right_type - self.op = op - - def __str__(self): - msg = "unsupported operand type(s) for {}: {!r} and {!r}" - return msg.format(self.op, self.left_type.name, self.right_type.name) - - -def _instancecheck(cls, other): - wrapped = cls.__wrapped__ - other_cls = other.__class__ - is_instance_of = wrapped is other_cls or issubclass(other_cls, wrapped) - warnings.warn( - "%r is deprecated and slated for removal in astroid " - "2.0, use %r instead" % (cls.__class__.__name__, wrapped.__name__), - PendingDeprecationWarning, - stacklevel=2, - ) - return is_instance_of - - -def proxy_alias(alias_name, node_type): - """Get a Proxy from the given name to the given node type.""" - proxy = type( - alias_name, - (lazy_object_proxy.Proxy,), - { - "__class__": object.__dict__["__class__"], - "__instancecheck__": _instancecheck, - }, - ) - return proxy(lambda: node_type) - - -def limit_inference(iterator, size): - """Limit inference amount. - - Limit inference amount to help with performance issues with - exponentially exploding possible results. - - :param iterator: Inference generator to limit - :type iterator: Iterator(NodeNG) - - :param size: Maximum mount of nodes yielded plus an - Uninferable at the end if limit reached - :type size: int - - :yields: A possibly modified generator - :rtype param: Iterable - """ - yield from islice(iterator, size) - has_more = next(iterator, False) - if has_more is not False: - yield Uninferable - return diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/beautifulsoup4-4.9.1.dist-info/AUTHORS b/Jobs_Collections/venv/Lib/python3.8/site-packages/beautifulsoup4-4.9.1.dist-info/AUTHORS deleted file mode 100644 index 1f14fe0..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/beautifulsoup4-4.9.1.dist-info/AUTHORS +++ /dev/null @@ -1,49 +0,0 @@ -Behold, mortal, the origins of Beautiful Soup... -================================================ - -Leonard Richardson is the primary maintainer. - -Aaron DeVore and Isaac Muse have made significant contributions to the -code base. - -Mark Pilgrim provided the encoding detection code that forms the base -of UnicodeDammit. - -Thomas Kluyver and Ezio Melotti finished the work of getting Beautiful -Soup 4 working under Python 3. - -Simon Willison wrote soupselect, which was used to make Beautiful Soup -support CSS selectors. Isaac Muse wrote SoupSieve, which made it -possible to _remove_ the CSS selector code from Beautiful Soup. - -Sam Ruby helped with a lot of edge cases. - -Jonathan Ellis was awarded the prestigious Beau Potage D'Or for his -work in solving the nestable tags conundrum. - -An incomplete list of people have contributed patches to Beautiful -Soup: - - Istvan Albert, Andrew Lin, Anthony Baxter, Oliver Beattie, Andrew -Boyko, Tony Chang, Francisco Canas, "Delong", Zephyr Fang, Fuzzy, -Roman Gaufman, Yoni Gilad, Richie Hindle, Toshihiro Kamiya, Peteris -Krumins, Kent Johnson, Marek Kapolka, Andreas Kostyrka, Roel Kramer, -Ben Last, Robert Leftwich, Stefaan Lippens, "liquider", Staffan -Malmgren, Ksenia Marasanova, JP Moins, Adam Monsen, John Nagle, "Jon", -Ed Oskiewicz, Martijn Peters, Greg Phillips, Giles Radford, Stefano -Revera, Arthur Rudolph, Marko Samastur, James Salter, Jouni Seppnen, -Alexander Schmolck, Tim Shirley, Geoffrey Sneddon, Ville Skytt, -"Vikas", Jens Svalgaard, Andy Theyers, Eric Weiser, Glyn Webster, John -Wiseman, Paul Wright, Danny Yoo - -An incomplete list of people who made suggestions or found bugs or -found ways to break Beautiful Soup: - - Hanno Bck, Matteo Bertini, Chris Curvey, Simon Cusack, Bruce Eckel, - Matt Ernst, Michael Foord, Tom Harris, Bill de hOra, Donald Howes, - Matt Patterson, Scott Roberts, Steve Strassmann, Mike Williams, - warchild at redho dot com, Sami Kuisma, Carlos Rocha, Bob Hutchison, - Joren Mc, Michal Migurski, John Kleven, Tim Heaney, Tripp Lilley, Ed - Summers, Dennis Sutch, Chris Smith, Aaron Swartz, Stuart - Turner, Greg Edwards, Kevin J Kalupson, Nikos Kouremenos, Artur de - Sousa Rocha, Yichun Wei, Per Vognsen diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/beautifulsoup4-4.9.1.dist-info/COPYING.txt b/Jobs_Collections/venv/Lib/python3.8/site-packages/beautifulsoup4-4.9.1.dist-info/COPYING.txt deleted file mode 100644 index fb6ae69..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/beautifulsoup4-4.9.1.dist-info/COPYING.txt +++ /dev/null @@ -1,27 +0,0 @@ -Beautiful Soup is made available under the MIT license: - - Copyright (c) 2004-2017 Leonard Richardson - - Permission is hereby granted, free of charge, to any person obtaining - a copy of this software and associated documentation files (the - "Software"), to deal in the Software without restriction, including - without limitation the rights to use, copy, modify, merge, publish, - distribute, sublicense, and/or sell copies of the Software, and to - permit persons to whom the Software is furnished to do so, subject to - the following conditions: - - The above copyright notice and this permission notice shall be - included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS - BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN - ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - SOFTWARE. - -Beautiful Soup incorporates code from the html5lib library, which is -also made available under the MIT license. Copyright (c) 2006-2013 -James Graham and other contributors diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/beautifulsoup4-4.9.1.dist-info/INSTALLER b/Jobs_Collections/venv/Lib/python3.8/site-packages/beautifulsoup4-4.9.1.dist-info/INSTALLER deleted file mode 100644 index a1b589e..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/beautifulsoup4-4.9.1.dist-info/INSTALLER +++ /dev/null @@ -1 +0,0 @@ -pip diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/beautifulsoup4-4.9.1.dist-info/LICENSE b/Jobs_Collections/venv/Lib/python3.8/site-packages/beautifulsoup4-4.9.1.dist-info/LICENSE deleted file mode 100644 index 4c068ba..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/beautifulsoup4-4.9.1.dist-info/LICENSE +++ /dev/null @@ -1,30 +0,0 @@ -Beautiful Soup is made available under the MIT license: - - Copyright (c) 2004-2019 Leonard Richardson - - Permission is hereby granted, free of charge, to any person obtaining - a copy of this software and associated documentation files (the - "Software"), to deal in the Software without restriction, including - without limitation the rights to use, copy, modify, merge, publish, - distribute, sublicense, and/or sell copies of the Software, and to - permit persons to whom the Software is furnished to do so, subject to - the following conditions: - - The above copyright notice and this permission notice shall be - included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS - BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN - ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - SOFTWARE. - -Beautiful Soup incorporates code from the html5lib library, which is -also made available under the MIT license. Copyright (c) 2006-2013 -James Graham and other contributors - -Beautiful Soup depends on the soupsieve library, which is also made -available under the MIT license. Copyright (c) 2018 Isaac Muse diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/beautifulsoup4-4.9.1.dist-info/METADATA b/Jobs_Collections/venv/Lib/python3.8/site-packages/beautifulsoup4-4.9.1.dist-info/METADATA deleted file mode 100644 index 1b4a564..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/beautifulsoup4-4.9.1.dist-info/METADATA +++ /dev/null @@ -1,131 +0,0 @@ -Metadata-Version: 2.1 -Name: beautifulsoup4 -Version: 4.9.1 -Summary: Screen-scraping library -Home-page: http://www.crummy.com/software/BeautifulSoup/bs4/ -Author: Leonard Richardson -Author-email: leonardr@segfault.org -License: MIT -Download-URL: http://www.crummy.com/software/BeautifulSoup/bs4/download/ -Platform: UNKNOWN -Classifier: Development Status :: 5 - Production/Stable -Classifier: Intended Audience :: Developers -Classifier: License :: OSI Approved :: MIT License -Classifier: Programming Language :: Python -Classifier: Programming Language :: Python :: 2.7 -Classifier: Programming Language :: Python :: 3 -Classifier: Topic :: Text Processing :: Markup :: HTML -Classifier: Topic :: Text Processing :: Markup :: XML -Classifier: Topic :: Text Processing :: Markup :: SGML -Classifier: Topic :: Software Development :: Libraries :: Python Modules -Description-Content-Type: text/markdown -Requires-Dist: soupsieve (>1.2) -Provides-Extra: html5lib -Requires-Dist: html5lib ; extra == 'html5lib' -Provides-Extra: lxml -Requires-Dist: lxml ; extra == 'lxml' - -Beautiful Soup is a library that makes it easy to scrape information -from web pages. It sits atop an HTML or XML parser, providing Pythonic -idioms for iterating, searching, and modifying the parse tree. - -# Quick start - -``` ->>> from bs4 import BeautifulSoup ->>> soup = BeautifulSoup("

SomebadHTML") ->>> print soup.prettify() - - -

-Some - -bad - -HTML - - -

- - ->>> soup.find(text="bad") -u'bad' ->>> soup.i -HTML -# ->>> soup = BeautifulSoup("SomebadXML", "xml") -# ->>> print soup.prettify() - - -Some - -bad - -XML - - -``` - -To go beyond the basics, [comprehensive documentation is available](http://www.crummy.com/software/BeautifulSoup/bs4/doc/). - -# Links - -* [Homepage](http://www.crummy.com/software/BeautifulSoup/bs4/) -* [Documentation](http://www.crummy.com/software/BeautifulSoup/bs4/doc/) -* [Discussion group](http://groups.google.com/group/beautifulsoup/) -* [Development](https://code.launchpad.net/beautifulsoup/) -* [Bug tracker](https://bugs.launchpad.net/beautifulsoup/) -* [Complete changelog](https://bazaar.launchpad.net/~leonardr/beautifulsoup/bs4/view/head:/CHANGELOG) - -# Note on Python 2 sunsetting - -Since 2012, Beautiful Soup has been developed as a Python 2 library -which is automatically converted to Python 3 code as necessary. This -makes it impossible to take advantage of some features of Python -3. - -For this reason, I plan to discontinue Beautiful Soup's Python 2 -support at some point after December 31, 2020: one year after the -sunset date for Python 2 itself. Beyond that point, new Beautiful Soup -development will exclusively target Python 3. Of course, older -releases of Beautiful Soup, which support both versions, will continue -to be available. - -# Supporting the project - -If you use Beautiful Soup as part of your professional work, please consider a -[Tidelift subscription](https://tidelift.com/subscription/pkg/pypi-beautifulsoup4?utm_source=pypi-beautifulsoup4&utm_medium=referral&utm_campaign=readme). -This will support many of the free software projects your organization -depends on, not just Beautiful Soup. - -If you use Beautiful Soup for personal projects, the best way to say -thank you is to read -[Tool Safety](https://www.crummy.com/software/BeautifulSoup/zine/), a zine I -wrote about what Beautiful Soup has taught me about software -development. - -# Building the documentation - -The bs4/doc/ directory contains full documentation in Sphinx -format. Run `make html` in that directory to create HTML -documentation. - -# Running the unit tests - -Beautiful Soup supports unit test discovery from the project root directory: - -``` -$ nosetests -``` - -``` -$ python -m unittest discover -s bs4 -``` - -If you checked out the source tree, you should see a script in the -home directory called test-all-versions. This script will run the unit -tests under Python 2, then create a temporary Python 3 conversion of -the source and run the unit tests again under Python 3. - - diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/beautifulsoup4-4.9.1.dist-info/RECORD b/Jobs_Collections/venv/Lib/python3.8/site-packages/beautifulsoup4-4.9.1.dist-info/RECORD deleted file mode 100644 index 46f1794..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/beautifulsoup4-4.9.1.dist-info/RECORD +++ /dev/null @@ -1,44 +0,0 @@ -beautifulsoup4-4.9.1.dist-info/AUTHORS,sha256=uSIdbrBb1sobdXl7VrlUvuvim2dN9kF3MH4Edn0WKGE,2176 -beautifulsoup4-4.9.1.dist-info/COPYING.txt,sha256=pH6lEjYJhGT-C09Vl0NZC1MwVtngD0nsv4Apn6tH4jE,1315 -beautifulsoup4-4.9.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 -beautifulsoup4-4.9.1.dist-info/LICENSE,sha256=ynIn3bnu1syAnhV_Z7Ag543eBjJAAB0RhW-FxJy25CM,1447 -beautifulsoup4-4.9.1.dist-info/METADATA,sha256=cIvKNOIcfpYqN5nITv3UDCtXZF1l_B5cPwpib-Gkjk8,4062 -beautifulsoup4-4.9.1.dist-info/RECORD,, -beautifulsoup4-4.9.1.dist-info/WHEEL,sha256=g4nMs7d-Xl9-xC9XovUrsDHGXt-FT0E17Yqo92DEfvY,92 -beautifulsoup4-4.9.1.dist-info/top_level.txt,sha256=H8VT-IuPWLzQqwG9_eChjXDJ1z0H9RRebdSR90Bjnkw,4 -bs4/__init__.py,sha256=ZM_Revj0Yipo_FRYdxS-rksn3MFXzR3XRyFirnM-h84,31551 -bs4/__pycache__/__init__.cpython-38.pyc,, -bs4/__pycache__/dammit.cpython-38.pyc,, -bs4/__pycache__/diagnose.cpython-38.pyc,, -bs4/__pycache__/element.cpython-38.pyc,, -bs4/__pycache__/formatter.cpython-38.pyc,, -bs4/__pycache__/testing.cpython-38.pyc,, -bs4/builder/__init__.py,sha256=VgrBobApHGLnuA8VCJuumZDP64UiGEzlxJJgLiV--sU,19841 -bs4/builder/__pycache__/__init__.cpython-38.pyc,, -bs4/builder/__pycache__/_html5lib.cpython-38.pyc,, -bs4/builder/__pycache__/_htmlparser.cpython-38.pyc,, -bs4/builder/__pycache__/_lxml.cpython-38.pyc,, -bs4/builder/_html5lib.py,sha256=hDxlzVrAku_eU7zEt4gZ-sAXzG58GvkLfMz6P4zUqoA,18748 -bs4/builder/_htmlparser.py,sha256=PEKGvBcJcf6_78CVwA1_uLxulnmnlRuWH0W2caTzpKk,18406 -bs4/builder/_lxml.py,sha256=e4w91RZi3NII_QYe2e1-EiN_BxQtgJPSRwQ8Xgz41ZA,12234 -bs4/dammit.py,sha256=k_XPB3kbZsHM01ckf9BxCUB2Eu2dIQ3d3DDt7UEv9RA,34130 -bs4/diagnose.py,sha256=HkiiFUWS9KU3sLILDYm8X-Tu0wZRuTdMClqtXPd99go,7761 -bs4/element.py,sha256=N6UNaAICZ0BjUl2VnZWZJz7b-v9W50R1YrCmaZbXw_0,81066 -bs4/formatter.py,sha256=Wayv1d6fUc9BSCa2k9uhvWwm89xCukdtJhyi9Sxvkuc,5654 -bs4/testing.py,sha256=xpDhC4AQaVrvNVog1Lgg8nUtg0Nack0CyEVD-bjAAj0,44897 -bs4/tests/__init__.py,sha256=bdUBDE750n7qNEfue7-3a1fBaUxJlvZMkvJvZa-lbYs,27 -bs4/tests/__pycache__/__init__.cpython-38.pyc,, -bs4/tests/__pycache__/test_builder_registry.cpython-38.pyc,, -bs4/tests/__pycache__/test_docs.cpython-38.pyc,, -bs4/tests/__pycache__/test_html5lib.cpython-38.pyc,, -bs4/tests/__pycache__/test_htmlparser.cpython-38.pyc,, -bs4/tests/__pycache__/test_lxml.cpython-38.pyc,, -bs4/tests/__pycache__/test_soup.cpython-38.pyc,, -bs4/tests/__pycache__/test_tree.cpython-38.pyc,, -bs4/tests/test_builder_registry.py,sha256=pllfRpArh9TYhjjRUiu1wITr9Ryyv4hiaAtRjij-k4E,5582 -bs4/tests/test_docs.py,sha256=FXfz2bGL4Xe0q6duwpmg9hmFiZuU4DVJPNZ0hTb6aH4,1067 -bs4/tests/test_html5lib.py,sha256=eWnLGHek_RO_TMq0Ixpb1RF3BEDrvhenMf2eaEBjjsg,6754 -bs4/tests/test_htmlparser.py,sha256=3294XvFbWVe0AYoTlnLPEDW_a0Om0BKRcsrwlJbxUaI,3941 -bs4/tests/test_lxml.py,sha256=xJr8eDrtHSb_vQw88lYEKyfdM1Hel4-dBaz14vQq78M,4105 -bs4/tests/test_soup.py,sha256=EhE1dhHKyctNu0y2l0ql6FOHg9qliEt8Kh7jfCx1lDw,29303 -bs4/tests/test_tree.py,sha256=W75j1-aDx8qHWzOr_JtRCjDE83nUShFauEzGfoys2k0,88988 diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/beautifulsoup4-4.9.1.dist-info/WHEEL b/Jobs_Collections/venv/Lib/python3.8/site-packages/beautifulsoup4-4.9.1.dist-info/WHEEL deleted file mode 100644 index b552003..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/beautifulsoup4-4.9.1.dist-info/WHEEL +++ /dev/null @@ -1,5 +0,0 @@ -Wheel-Version: 1.0 -Generator: bdist_wheel (0.34.2) -Root-Is-Purelib: true -Tag: py3-none-any - diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/beautifulsoup4-4.9.1.dist-info/top_level.txt b/Jobs_Collections/venv/Lib/python3.8/site-packages/beautifulsoup4-4.9.1.dist-info/top_level.txt deleted file mode 100644 index 1315442..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/beautifulsoup4-4.9.1.dist-info/top_level.txt +++ /dev/null @@ -1 +0,0 @@ -bs4 diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4-0.0.1-py3.8.egg-info/PKG-INFO b/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4-0.0.1-py3.8.egg-info/PKG-INFO deleted file mode 100644 index 60137e4..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4-0.0.1-py3.8.egg-info/PKG-INFO +++ /dev/null @@ -1,21 +0,0 @@ -Metadata-Version: 1.1 -Name: bs4 -Version: 0.0.1 -Summary: Screen-scraping library -Home-page: https://pypi.python.org/pypi/beautifulsoup4 -Author: Leonard Richardson -Author-email: leonardr@segfault.org -License: MIT -Download-URL: http://www.crummy.com/software/BeautifulSoup/bs4/download/ -Description: Use `beautifulsoup4 `_ instead. -Platform: UNKNOWN -Classifier: Development Status :: 5 - Production/Stable -Classifier: Intended Audience :: Developers -Classifier: License :: OSI Approved :: MIT License -Classifier: Programming Language :: Python -Classifier: Programming Language :: Python :: 2 -Classifier: Programming Language :: Python :: 3 -Classifier: Topic :: Text Processing :: Markup :: HTML -Classifier: Topic :: Text Processing :: Markup :: XML -Classifier: Topic :: Text Processing :: Markup :: SGML -Classifier: Topic :: Software Development :: Libraries :: Python Modules diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4-0.0.1-py3.8.egg-info/SOURCES.txt b/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4-0.0.1-py3.8.egg-info/SOURCES.txt deleted file mode 100644 index b46d1c5..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4-0.0.1-py3.8.egg-info/SOURCES.txt +++ /dev/null @@ -1,7 +0,0 @@ -setup.cfg -setup.py -bs4.egg-info/PKG-INFO -bs4.egg-info/SOURCES.txt -bs4.egg-info/dependency_links.txt -bs4.egg-info/requires.txt -bs4.egg-info/top_level.txt \ No newline at end of file diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4-0.0.1-py3.8.egg-info/dependency_links.txt b/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4-0.0.1-py3.8.egg-info/dependency_links.txt deleted file mode 100644 index 8b13789..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4-0.0.1-py3.8.egg-info/dependency_links.txt +++ /dev/null @@ -1 +0,0 @@ - diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4-0.0.1-py3.8.egg-info/installed-files.txt b/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4-0.0.1-py3.8.egg-info/installed-files.txt deleted file mode 100644 index 62cfadb..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4-0.0.1-py3.8.egg-info/installed-files.txt +++ /dev/null @@ -1,5 +0,0 @@ -PKG-INFO -SOURCES.txt -dependency_links.txt -requires.txt -top_level.txt diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4-0.0.1-py3.8.egg-info/requires.txt b/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4-0.0.1-py3.8.egg-info/requires.txt deleted file mode 100644 index c1f5f71..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4-0.0.1-py3.8.egg-info/requires.txt +++ /dev/null @@ -1 +0,0 @@ -beautifulsoup4 diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4-0.0.1-py3.8.egg-info/top_level.txt b/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4-0.0.1-py3.8.egg-info/top_level.txt deleted file mode 100644 index 8b13789..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4-0.0.1-py3.8.egg-info/top_level.txt +++ /dev/null @@ -1 +0,0 @@ - diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4/__init__.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4/__init__.py deleted file mode 100644 index afaca71..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4/__init__.py +++ /dev/null @@ -1,777 +0,0 @@ -"""Beautiful Soup Elixir and Tonic - "The Screen-Scraper's Friend". - -http://www.crummy.com/software/BeautifulSoup/ - -Beautiful Soup uses a pluggable XML or HTML parser to parse a -(possibly invalid) document into a tree representation. Beautiful Soup -provides methods and Pythonic idioms that make it easy to navigate, -search, and modify the parse tree. - -Beautiful Soup works with Python 2.7 and up. It works better if lxml -and/or html5lib is installed. - -For more than you ever wanted to know about Beautiful Soup, see the -documentation: http://www.crummy.com/software/BeautifulSoup/bs4/doc/ -""" - -__author__ = "Leonard Richardson (leonardr@segfault.org)" -__version__ = "4.9.1" -__copyright__ = "Copyright (c) 2004-2020 Leonard Richardson" -# Use of this source code is governed by the MIT license. -__license__ = "MIT" - -__all__ = ['BeautifulSoup'] - -import os -import re -import sys -import traceback -import warnings - -from .builder import builder_registry, ParserRejectedMarkup -from .dammit import UnicodeDammit -from .element import ( - CData, - Comment, - DEFAULT_OUTPUT_ENCODING, - Declaration, - Doctype, - NavigableString, - PageElement, - ProcessingInstruction, - PYTHON_SPECIFIC_ENCODINGS, - ResultSet, - Script, - Stylesheet, - SoupStrainer, - Tag, - TemplateString, - ) - -# The very first thing we do is give a useful error if someone is -# running this code under Python 3 without converting it. -'You are trying to run the Python 2 version of Beautiful Soup under Python 3. This will not work.'!='You need to convert the code, either by installing it (`python setup.py install`) or by running 2to3 (`2to3 -w bs4`).' - -# Define some custom warnings. -class GuessedAtParserWarning(UserWarning): - """The warning issued when BeautifulSoup has to guess what parser to - use -- probably because no parser was specified in the constructor. - """ - -class MarkupResemblesLocatorWarning(UserWarning): - """The warning issued when BeautifulSoup is given 'markup' that - actually looks like a resource locator -- a URL or a path to a file - on disk. - """ - - -class BeautifulSoup(Tag): - """A data structure representing a parsed HTML or XML document. - - Most of the methods you'll call on a BeautifulSoup object are inherited from - PageElement or Tag. - - Internally, this class defines the basic interface called by the - tree builders when converting an HTML/XML document into a data - structure. The interface abstracts away the differences between - parsers. To write a new tree builder, you'll need to understand - these methods as a whole. - - These methods will be called by the BeautifulSoup constructor: - * reset() - * feed(markup) - - The tree builder may call these methods from its feed() implementation: - * handle_starttag(name, attrs) # See note about return value - * handle_endtag(name) - * handle_data(data) # Appends to the current data node - * endData(containerClass) # Ends the current data node - - No matter how complicated the underlying parser is, you should be - able to build a tree using 'start tag' events, 'end tag' events, - 'data' events, and "done with data" events. - - If you encounter an empty-element tag (aka a self-closing tag, - like HTML's
tag), call handle_starttag and then - handle_endtag. - """ - - # Since BeautifulSoup subclasses Tag, it's possible to treat it as - # a Tag with a .name. This name makes it clear the BeautifulSoup - # object isn't a real markup tag. - ROOT_TAG_NAME = '[document]' - - # If the end-user gives no indication which tree builder they - # want, look for one with these features. - DEFAULT_BUILDER_FEATURES = ['html', 'fast'] - - # A string containing all ASCII whitespace characters, used in - # endData() to detect data chunks that seem 'empty'. - ASCII_SPACES = '\x20\x0a\x09\x0c\x0d' - - NO_PARSER_SPECIFIED_WARNING = "No parser was explicitly specified, so I'm using the best available %(markup_type)s parser for this system (\"%(parser)s\"). This usually isn't a problem, but if you run this code on another system, or in a different virtual environment, it may use a different parser and behave differently.\n\nThe code that caused this warning is on line %(line_number)s of the file %(filename)s. To get rid of this warning, pass the additional argument 'features=\"%(parser)s\"' to the BeautifulSoup constructor.\n" - - def __init__(self, markup="", features=None, builder=None, - parse_only=None, from_encoding=None, exclude_encodings=None, - element_classes=None, **kwargs): - """Constructor. - - :param markup: A string or a file-like object representing - markup to be parsed. - - :param features: Desirable features of the parser to be - used. This may be the name of a specific parser ("lxml", - "lxml-xml", "html.parser", or "html5lib") or it may be the - type of markup to be used ("html", "html5", "xml"). It's - recommended that you name a specific parser, so that - Beautiful Soup gives you the same results across platforms - and virtual environments. - - :param builder: A TreeBuilder subclass to instantiate (or - instance to use) instead of looking one up based on - `features`. You only need to use this if you've implemented a - custom TreeBuilder. - - :param parse_only: A SoupStrainer. Only parts of the document - matching the SoupStrainer will be considered. This is useful - when parsing part of a document that would otherwise be too - large to fit into memory. - - :param from_encoding: A string indicating the encoding of the - document to be parsed. Pass this in if Beautiful Soup is - guessing wrongly about the document's encoding. - - :param exclude_encodings: A list of strings indicating - encodings known to be wrong. Pass this in if you don't know - the document's encoding but you know Beautiful Soup's guess is - wrong. - - :param element_classes: A dictionary mapping BeautifulSoup - classes like Tag and NavigableString, to other classes you'd - like to be instantiated instead as the parse tree is - built. This is useful for subclassing Tag or NavigableString - to modify default behavior. - - :param kwargs: For backwards compatibility purposes, the - constructor accepts certain keyword arguments used in - Beautiful Soup 3. None of these arguments do anything in - Beautiful Soup 4; they will result in a warning and then be - ignored. - - Apart from this, any keyword arguments passed into the - BeautifulSoup constructor are propagated to the TreeBuilder - constructor. This makes it possible to configure a - TreeBuilder by passing in arguments, not just by saying which - one to use. - """ - if 'convertEntities' in kwargs: - del kwargs['convertEntities'] - warnings.warn( - "BS4 does not respect the convertEntities argument to the " - "BeautifulSoup constructor. Entities are always converted " - "to Unicode characters.") - - if 'markupMassage' in kwargs: - del kwargs['markupMassage'] - warnings.warn( - "BS4 does not respect the markupMassage argument to the " - "BeautifulSoup constructor. The tree builder is responsible " - "for any necessary markup massage.") - - if 'smartQuotesTo' in kwargs: - del kwargs['smartQuotesTo'] - warnings.warn( - "BS4 does not respect the smartQuotesTo argument to the " - "BeautifulSoup constructor. Smart quotes are always converted " - "to Unicode characters.") - - if 'selfClosingTags' in kwargs: - del kwargs['selfClosingTags'] - warnings.warn( - "BS4 does not respect the selfClosingTags argument to the " - "BeautifulSoup constructor. The tree builder is responsible " - "for understanding self-closing tags.") - - if 'isHTML' in kwargs: - del kwargs['isHTML'] - warnings.warn( - "BS4 does not respect the isHTML argument to the " - "BeautifulSoup constructor. Suggest you use " - "features='lxml' for HTML and features='lxml-xml' for " - "XML.") - - def deprecated_argument(old_name, new_name): - if old_name in kwargs: - warnings.warn( - 'The "%s" argument to the BeautifulSoup constructor ' - 'has been renamed to "%s."' % (old_name, new_name)) - value = kwargs[old_name] - del kwargs[old_name] - return value - return None - - parse_only = parse_only or deprecated_argument( - "parseOnlyThese", "parse_only") - - from_encoding = from_encoding or deprecated_argument( - "fromEncoding", "from_encoding") - - if from_encoding and isinstance(markup, str): - warnings.warn("You provided Unicode markup but also provided a value for from_encoding. Your from_encoding will be ignored.") - from_encoding = None - - self.element_classes = element_classes or dict() - - # We need this information to track whether or not the builder - # was specified well enough that we can omit the 'you need to - # specify a parser' warning. - original_builder = builder - original_features = features - - if isinstance(builder, type): - # A builder class was passed in; it needs to be instantiated. - builder_class = builder - builder = None - elif builder is None: - if isinstance(features, str): - features = [features] - if features is None or len(features) == 0: - features = self.DEFAULT_BUILDER_FEATURES - builder_class = builder_registry.lookup(*features) - if builder_class is None: - raise FeatureNotFound( - "Couldn't find a tree builder with the features you " - "requested: %s. Do you need to install a parser library?" - % ",".join(features)) - - # At this point either we have a TreeBuilder instance in - # builder, or we have a builder_class that we can instantiate - # with the remaining **kwargs. - if builder is None: - builder = builder_class(**kwargs) - if not original_builder and not ( - original_features == builder.NAME or - original_features in builder.ALTERNATE_NAMES - ): - if builder.is_xml: - markup_type = "XML" - else: - markup_type = "HTML" - - # This code adapted from warnings.py so that we get the same line - # of code as our warnings.warn() call gets, even if the answer is wrong - # (as it may be in a multithreading situation). - caller = None - try: - caller = sys._getframe(1) - except ValueError: - pass - if caller: - globals = caller.f_globals - line_number = caller.f_lineno - else: - globals = sys.__dict__ - line_number= 1 - filename = globals.get('__file__') - if filename: - fnl = filename.lower() - if fnl.endswith((".pyc", ".pyo")): - filename = filename[:-1] - if filename: - # If there is no filename at all, the user is most likely in a REPL, - # and the warning is not necessary. - values = dict( - filename=filename, - line_number=line_number, - parser=builder.NAME, - markup_type=markup_type - ) - warnings.warn( - self.NO_PARSER_SPECIFIED_WARNING % values, - GuessedAtParserWarning, stacklevel=2 - ) - else: - if kwargs: - warnings.warn("Keyword arguments to the BeautifulSoup constructor will be ignored. These would normally be passed into the TreeBuilder constructor, but a TreeBuilder instance was passed in as `builder`.") - - self.builder = builder - self.is_xml = builder.is_xml - self.known_xml = self.is_xml - self._namespaces = dict() - self.parse_only = parse_only - - self.builder.initialize_soup(self) - - if hasattr(markup, 'read'): # It's a file-type object. - markup = markup.read() - elif len(markup) <= 256 and ( - (isinstance(markup, bytes) and not b'<' in markup) - or (isinstance(markup, str) and not '<' in markup) - ): - # Print out warnings for a couple beginner problems - # involving passing non-markup to Beautiful Soup. - # Beautiful Soup will still parse the input as markup, - # just in case that's what the user really wants. - if (isinstance(markup, str) - and not os.path.supports_unicode_filenames): - possible_filename = markup.encode("utf8") - else: - possible_filename = markup - is_file = False - try: - is_file = os.path.exists(possible_filename) - except Exception as e: - # This is almost certainly a problem involving - # characters not valid in filenames on this - # system. Just let it go. - pass - if is_file: - warnings.warn( - '"%s" looks like a filename, not markup. You should' - ' probably open this file and pass the filehandle into' - ' Beautiful Soup.' % self._decode_markup(markup), - MarkupResemblesLocatorWarning - ) - self._check_markup_is_url(markup) - - rejections = [] - success = False - for (self.markup, self.original_encoding, self.declared_html_encoding, - self.contains_replacement_characters) in ( - self.builder.prepare_markup( - markup, from_encoding, exclude_encodings=exclude_encodings)): - self.reset() - try: - self._feed() - success = True - break - except ParserRejectedMarkup as e: - rejections.append(e) - pass - - if not success: - other_exceptions = [str(e) for e in rejections] - raise ParserRejectedMarkup( - "The markup you provided was rejected by the parser. Trying a different parser or a different encoding may help.\n\nOriginal exception(s) from parser:\n " + "\n ".join(other_exceptions) - ) - - # Clear out the markup and remove the builder's circular - # reference to this object. - self.markup = None - self.builder.soup = None - - def __copy__(self): - """Copy a BeautifulSoup object by converting the document to a string and parsing it again.""" - copy = type(self)( - self.encode('utf-8'), builder=self.builder, from_encoding='utf-8' - ) - - # Although we encoded the tree to UTF-8, that may not have - # been the encoding of the original markup. Set the copy's - # .original_encoding to reflect the original object's - # .original_encoding. - copy.original_encoding = self.original_encoding - return copy - - def __getstate__(self): - # Frequently a tree builder can't be pickled. - d = dict(self.__dict__) - if 'builder' in d and not self.builder.picklable: - d['builder'] = None - return d - - @classmethod - def _decode_markup(cls, markup): - """Ensure `markup` is bytes so it's safe to send into warnings.warn. - - TODO: warnings.warn had this problem back in 2010 but it might not - anymore. - """ - if isinstance(markup, bytes): - decoded = markup.decode('utf-8', 'replace') - else: - decoded = markup - return decoded - - @classmethod - def _check_markup_is_url(cls, markup): - """Error-handling method to raise a warning if incoming markup looks - like a URL. - - :param markup: A string. - """ - if isinstance(markup, bytes): - space = b' ' - cant_start_with = (b"http:", b"https:") - elif isinstance(markup, str): - space = ' ' - cant_start_with = ("http:", "https:") - else: - return - - if any(markup.startswith(prefix) for prefix in cant_start_with): - if not space in markup: - warnings.warn( - '"%s" looks like a URL. Beautiful Soup is not an' - ' HTTP client. You should probably use an HTTP client like' - ' requests to get the document behind the URL, and feed' - ' that document to Beautiful Soup.' % cls._decode_markup( - markup - ), - MarkupResemblesLocatorWarning - ) - - def _feed(self): - """Internal method that parses previously set markup, creating a large - number of Tag and NavigableString objects. - """ - # Convert the document to Unicode. - self.builder.reset() - - self.builder.feed(self.markup) - # Close out any unfinished strings and close all the open tags. - self.endData() - while self.currentTag.name != self.ROOT_TAG_NAME: - self.popTag() - - def reset(self): - """Reset this object to a state as though it had never parsed any - markup. - """ - Tag.__init__(self, self, self.builder, self.ROOT_TAG_NAME) - self.hidden = 1 - self.builder.reset() - self.current_data = [] - self.currentTag = None - self.tagStack = [] - self.preserve_whitespace_tag_stack = [] - self.string_container_stack = [] - self.pushTag(self) - - def new_tag(self, name, namespace=None, nsprefix=None, attrs={}, - sourceline=None, sourcepos=None, **kwattrs): - """Create a new Tag associated with this BeautifulSoup object. - - :param name: The name of the new Tag. - :param namespace: The URI of the new Tag's XML namespace, if any. - :param prefix: The prefix for the new Tag's XML namespace, if any. - :param attrs: A dictionary of this Tag's attribute values; can - be used instead of `kwattrs` for attributes like 'class' - that are reserved words in Python. - :param sourceline: The line number where this tag was - (purportedly) found in its source document. - :param sourcepos: The character position within `sourceline` where this - tag was (purportedly) found. - :param kwattrs: Keyword arguments for the new Tag's attribute values. - - """ - kwattrs.update(attrs) - return self.element_classes.get(Tag, Tag)( - None, self.builder, name, namespace, nsprefix, kwattrs, - sourceline=sourceline, sourcepos=sourcepos - ) - - def string_container(self, base_class=None): - container = base_class or NavigableString - - # There may be a general override of NavigableString. - container = self.element_classes.get( - container, container - ) - - # On top of that, we may be inside a tag that needs a special - # container class. - if self.string_container_stack: - container = self.builder.string_containers.get( - self.string_container_stack[-1].name, container - ) - return container - - def new_string(self, s, subclass=None): - """Create a new NavigableString associated with this BeautifulSoup - object. - """ - container = self.string_container(subclass) - return container(s) - - def insert_before(self, successor): - """This method is part of the PageElement API, but `BeautifulSoup` doesn't implement - it because there is nothing before or after it in the parse tree. - """ - raise NotImplementedError("BeautifulSoup objects don't support insert_before().") - - def insert_after(self, successor): - """This method is part of the PageElement API, but `BeautifulSoup` doesn't implement - it because there is nothing before or after it in the parse tree. - """ - raise NotImplementedError("BeautifulSoup objects don't support insert_after().") - - def popTag(self): - """Internal method called by _popToTag when a tag is closed.""" - tag = self.tagStack.pop() - if self.preserve_whitespace_tag_stack and tag == self.preserve_whitespace_tag_stack[-1]: - self.preserve_whitespace_tag_stack.pop() - if self.string_container_stack and tag == self.string_container_stack[-1]: - self.string_container_stack.pop() - #print("Pop", tag.name) - if self.tagStack: - self.currentTag = self.tagStack[-1] - return self.currentTag - - def pushTag(self, tag): - """Internal method called by handle_starttag when a tag is opened.""" - #print("Push", tag.name) - if self.currentTag is not None: - self.currentTag.contents.append(tag) - self.tagStack.append(tag) - self.currentTag = self.tagStack[-1] - if tag.name in self.builder.preserve_whitespace_tags: - self.preserve_whitespace_tag_stack.append(tag) - if tag.name in self.builder.string_containers: - self.string_container_stack.append(tag) - - def endData(self, containerClass=None): - """Method called by the TreeBuilder when the end of a data segment - occurs. - """ - containerClass = self.string_container(containerClass) - - if self.current_data: - current_data = ''.join(self.current_data) - # If whitespace is not preserved, and this string contains - # nothing but ASCII spaces, replace it with a single space - # or newline. - if not self.preserve_whitespace_tag_stack: - strippable = True - for i in current_data: - if i not in self.ASCII_SPACES: - strippable = False - break - if strippable: - if '\n' in current_data: - current_data = '\n' - else: - current_data = ' ' - - # Reset the data collector. - self.current_data = [] - - # Should we add this string to the tree at all? - if self.parse_only and len(self.tagStack) <= 1 and \ - (not self.parse_only.text or \ - not self.parse_only.search(current_data)): - return - - o = containerClass(current_data) - self.object_was_parsed(o) - - def object_was_parsed(self, o, parent=None, most_recent_element=None): - """Method called by the TreeBuilder to integrate an object into the parse tree.""" - if parent is None: - parent = self.currentTag - if most_recent_element is not None: - previous_element = most_recent_element - else: - previous_element = self._most_recent_element - - next_element = previous_sibling = next_sibling = None - if isinstance(o, Tag): - next_element = o.next_element - next_sibling = o.next_sibling - previous_sibling = o.previous_sibling - if previous_element is None: - previous_element = o.previous_element - - fix = parent.next_element is not None - - o.setup(parent, previous_element, next_element, previous_sibling, next_sibling) - - self._most_recent_element = o - parent.contents.append(o) - - # Check if we are inserting into an already parsed node. - if fix: - self._linkage_fixer(parent) - - def _linkage_fixer(self, el): - """Make sure linkage of this fragment is sound.""" - - first = el.contents[0] - child = el.contents[-1] - descendant = child - - if child is first and el.parent is not None: - # Parent should be linked to first child - el.next_element = child - # We are no longer linked to whatever this element is - prev_el = child.previous_element - if prev_el is not None and prev_el is not el: - prev_el.next_element = None - # First child should be linked to the parent, and no previous siblings. - child.previous_element = el - child.previous_sibling = None - - # We have no sibling as we've been appended as the last. - child.next_sibling = None - - # This index is a tag, dig deeper for a "last descendant" - if isinstance(child, Tag) and child.contents: - descendant = child._last_descendant(False) - - # As the final step, link last descendant. It should be linked - # to the parent's next sibling (if found), else walk up the chain - # and find a parent with a sibling. It should have no next sibling. - descendant.next_element = None - descendant.next_sibling = None - target = el - while True: - if target is None: - break - elif target.next_sibling is not None: - descendant.next_element = target.next_sibling - target.next_sibling.previous_element = child - break - target = target.parent - - def _popToTag(self, name, nsprefix=None, inclusivePop=True): - """Pops the tag stack up to and including the most recent - instance of the given tag. - - :param name: Pop up to the most recent tag with this name. - :param nsprefix: The namespace prefix that goes with `name`. - :param inclusivePop: It this is false, pops the tag stack up - to but *not* including the most recent instqance of the - given tag. - """ - #print("Popping to %s" % name) - if name == self.ROOT_TAG_NAME: - # The BeautifulSoup object itself can never be popped. - return - - most_recently_popped = None - - stack_size = len(self.tagStack) - for i in range(stack_size - 1, 0, -1): - t = self.tagStack[i] - if (name == t.name and nsprefix == t.prefix): - if inclusivePop: - most_recently_popped = self.popTag() - break - most_recently_popped = self.popTag() - - return most_recently_popped - - def handle_starttag(self, name, namespace, nsprefix, attrs, sourceline=None, - sourcepos=None): - """Called by the tree builder when a new tag is encountered. - - :param name: Name of the tag. - :param nsprefix: Namespace prefix for the tag. - :param attrs: A dictionary of attribute values. - :param sourceline: The line number where this tag was found in its - source document. - :param sourcepos: The character position within `sourceline` where this - tag was found. - - If this method returns None, the tag was rejected by an active - SoupStrainer. You should proceed as if the tag had not occurred - in the document. For instance, if this was a self-closing tag, - don't call handle_endtag. - """ - # print("Start tag %s: %s" % (name, attrs)) - self.endData() - - if (self.parse_only and len(self.tagStack) <= 1 - and (self.parse_only.text - or not self.parse_only.search_tag(name, attrs))): - return None - - tag = self.element_classes.get(Tag, Tag)( - self, self.builder, name, namespace, nsprefix, attrs, - self.currentTag, self._most_recent_element, - sourceline=sourceline, sourcepos=sourcepos - ) - if tag is None: - return tag - if self._most_recent_element is not None: - self._most_recent_element.next_element = tag - self._most_recent_element = tag - self.pushTag(tag) - return tag - - def handle_endtag(self, name, nsprefix=None): - """Called by the tree builder when an ending tag is encountered. - - :param name: Name of the tag. - :param nsprefix: Namespace prefix for the tag. - """ - #print("End tag: " + name) - self.endData() - self._popToTag(name, nsprefix) - - def handle_data(self, data): - """Called by the tree builder when a chunk of textual data is encountered.""" - self.current_data.append(data) - - def decode(self, pretty_print=False, - eventual_encoding=DEFAULT_OUTPUT_ENCODING, - formatter="minimal"): - """Returns a string or Unicode representation of the parse tree - as an HTML or XML document. - - :param pretty_print: If this is True, indentation will be used to - make the document more readable. - :param eventual_encoding: The encoding of the final document. - If this is None, the document will be a Unicode string. - """ - if self.is_xml: - # Print the XML declaration - encoding_part = '' - if eventual_encoding in PYTHON_SPECIFIC_ENCODINGS: - # This is a special Python encoding; it can't actually - # go into an XML document because it means nothing - # outside of Python. - eventual_encoding = None - if eventual_encoding != None: - encoding_part = ' encoding="%s"' % eventual_encoding - prefix = '\n' % encoding_part - else: - prefix = '' - if not pretty_print: - indent_level = None - else: - indent_level = 0 - return prefix + super(BeautifulSoup, self).decode( - indent_level, eventual_encoding, formatter) - -# Aliases to make it easier to get started quickly, e.g. 'from bs4 import _soup' -_s = BeautifulSoup -_soup = BeautifulSoup - -class BeautifulStoneSoup(BeautifulSoup): - """Deprecated interface to an XML parser.""" - - def __init__(self, *args, **kwargs): - kwargs['features'] = 'xml' - warnings.warn( - 'The BeautifulStoneSoup class is deprecated. Instead of using ' - 'it, pass features="xml" into the BeautifulSoup constructor.') - super(BeautifulStoneSoup, self).__init__(*args, **kwargs) - - -class StopParsing(Exception): - """Exception raised by a TreeBuilder if it's unable to continue parsing.""" - pass - -class FeatureNotFound(ValueError): - """Exception raised by the BeautifulSoup constructor if no parser with the - requested features is found. - """ - pass - - -#If this file is run as a script, act as an HTML pretty-printer. -if __name__ == '__main__': - import sys - soup = BeautifulSoup(sys.stdin) - print((soup.prettify())) diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4/__pycache__/__init__.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4/__pycache__/__init__.cpython-38.pyc deleted file mode 100644 index 298b83f..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4/__pycache__/__init__.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4/__pycache__/dammit.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4/__pycache__/dammit.cpython-38.pyc deleted file mode 100644 index d51fa5e..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4/__pycache__/dammit.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4/__pycache__/diagnose.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4/__pycache__/diagnose.cpython-38.pyc deleted file mode 100644 index 04f5e58..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4/__pycache__/diagnose.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4/__pycache__/element.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4/__pycache__/element.cpython-38.pyc deleted file mode 100644 index 515d004..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4/__pycache__/element.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4/__pycache__/formatter.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4/__pycache__/formatter.cpython-38.pyc deleted file mode 100644 index 7a48bdc..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4/__pycache__/formatter.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4/__pycache__/testing.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4/__pycache__/testing.cpython-38.pyc deleted file mode 100644 index 6e9c9ce..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4/__pycache__/testing.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4/builder/__init__.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4/builder/__init__.py deleted file mode 100644 index 86759db..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4/builder/__init__.py +++ /dev/null @@ -1,520 +0,0 @@ -# Use of this source code is governed by the MIT license. -__license__ = "MIT" - -from collections import defaultdict -import itertools -import sys -from bs4.element import ( - CharsetMetaAttributeValue, - ContentMetaAttributeValue, - Stylesheet, - Script, - TemplateString, - nonwhitespace_re -) - -__all__ = [ - 'HTMLTreeBuilder', - 'SAXTreeBuilder', - 'TreeBuilder', - 'TreeBuilderRegistry', - ] - -# Some useful features for a TreeBuilder to have. -FAST = 'fast' -PERMISSIVE = 'permissive' -STRICT = 'strict' -XML = 'xml' -HTML = 'html' -HTML_5 = 'html5' - - -class TreeBuilderRegistry(object): - """A way of looking up TreeBuilder subclasses by their name or by desired - features. - """ - - def __init__(self): - self.builders_for_feature = defaultdict(list) - self.builders = [] - - def register(self, treebuilder_class): - """Register a treebuilder based on its advertised features. - - :param treebuilder_class: A subclass of Treebuilder. its .features - attribute should list its features. - """ - for feature in treebuilder_class.features: - self.builders_for_feature[feature].insert(0, treebuilder_class) - self.builders.insert(0, treebuilder_class) - - def lookup(self, *features): - """Look up a TreeBuilder subclass with the desired features. - - :param features: A list of features to look for. If none are - provided, the most recently registered TreeBuilder subclass - will be used. - :return: A TreeBuilder subclass, or None if there's no - registered subclass with all the requested features. - """ - if len(self.builders) == 0: - # There are no builders at all. - return None - - if len(features) == 0: - # They didn't ask for any features. Give them the most - # recently registered builder. - return self.builders[0] - - # Go down the list of features in order, and eliminate any builders - # that don't match every feature. - features = list(features) - features.reverse() - candidates = None - candidate_set = None - while len(features) > 0: - feature = features.pop() - we_have_the_feature = self.builders_for_feature.get(feature, []) - if len(we_have_the_feature) > 0: - if candidates is None: - candidates = we_have_the_feature - candidate_set = set(candidates) - else: - # Eliminate any candidates that don't have this feature. - candidate_set = candidate_set.intersection( - set(we_have_the_feature)) - - # The only valid candidates are the ones in candidate_set. - # Go through the original list of candidates and pick the first one - # that's in candidate_set. - if candidate_set is None: - return None - for candidate in candidates: - if candidate in candidate_set: - return candidate - return None - -# The BeautifulSoup class will take feature lists from developers and use them -# to look up builders in this registry. -builder_registry = TreeBuilderRegistry() - -class TreeBuilder(object): - """Turn a textual document into a Beautiful Soup object tree.""" - - NAME = "[Unknown tree builder]" - ALTERNATE_NAMES = [] - features = [] - - is_xml = False - picklable = False - empty_element_tags = None # A tag will be considered an empty-element - # tag when and only when it has no contents. - - # A value for these tag/attribute combinations is a space- or - # comma-separated list of CDATA, rather than a single CDATA. - DEFAULT_CDATA_LIST_ATTRIBUTES = {} - - # Whitespace should be preserved inside these tags. - DEFAULT_PRESERVE_WHITESPACE_TAGS = set() - - # The textual contents of tags with these names should be - # instantiated with some class other than NavigableString. - DEFAULT_STRING_CONTAINERS = {} - - USE_DEFAULT = object() - - # Most parsers don't keep track of line numbers. - TRACKS_LINE_NUMBERS = False - - def __init__(self, multi_valued_attributes=USE_DEFAULT, - preserve_whitespace_tags=USE_DEFAULT, - store_line_numbers=USE_DEFAULT, - string_containers=USE_DEFAULT, - ): - """Constructor. - - :param multi_valued_attributes: If this is set to None, the - TreeBuilder will not turn any values for attributes like - 'class' into lists. Setting this to a dictionary will - customize this behavior; look at DEFAULT_CDATA_LIST_ATTRIBUTES - for an example. - - Internally, these are called "CDATA list attributes", but that - probably doesn't make sense to an end-user, so the argument name - is `multi_valued_attributes`. - - :param preserve_whitespace_tags: A list of tags to treat - the way
 tags are treated in HTML. Tags in this list
-         are immune from pretty-printing; their contents will always be
-         output as-is.
-
-        :param string_containers: A dictionary mapping tag names to
-        the classes that should be instantiated to contain the textual
-        contents of those tags. The default is to use NavigableString
-        for every tag, no matter what the name. You can override the
-        default by changing DEFAULT_STRING_CONTAINERS.
-
-        :param store_line_numbers: If the parser keeps track of the
-         line numbers and positions of the original markup, that
-         information will, by default, be stored in each corresponding
-         `Tag` object. You can turn this off by passing
-         store_line_numbers=False. If the parser you're using doesn't 
-         keep track of this information, then setting store_line_numbers=True
-         will do nothing.
-        """
-        self.soup = None
-        if multi_valued_attributes is self.USE_DEFAULT:
-            multi_valued_attributes = self.DEFAULT_CDATA_LIST_ATTRIBUTES
-        self.cdata_list_attributes = multi_valued_attributes
-        if preserve_whitespace_tags is self.USE_DEFAULT:
-            preserve_whitespace_tags = self.DEFAULT_PRESERVE_WHITESPACE_TAGS
-        self.preserve_whitespace_tags = preserve_whitespace_tags
-        if store_line_numbers == self.USE_DEFAULT:
-            store_line_numbers = self.TRACKS_LINE_NUMBERS
-        self.store_line_numbers = store_line_numbers 
-        if string_containers == self.USE_DEFAULT:
-            string_containers = self.DEFAULT_STRING_CONTAINERS
-        self.string_containers = string_containers
-        
-    def initialize_soup(self, soup):
-        """The BeautifulSoup object has been initialized and is now
-        being associated with the TreeBuilder.
-
-        :param soup: A BeautifulSoup object.
-        """
-        self.soup = soup
-        
-    def reset(self):
-        """Do any work necessary to reset the underlying parser
-        for a new document.
-
-        By default, this does nothing.
-        """
-        pass
-
-    def can_be_empty_element(self, tag_name):
-        """Might a tag with this name be an empty-element tag?
-
-        The final markup may or may not actually present this tag as
-        self-closing.
-
-        For instance: an HTMLBuilder does not consider a 

tag to be - an empty-element tag (it's not in - HTMLBuilder.empty_element_tags). This means an empty

tag - will be presented as "

", not "

" or "

". - - The default implementation has no opinion about which tags are - empty-element tags, so a tag will be presented as an - empty-element tag if and only if it has no children. - "" will become "", and "bar" will - be left alone. - - :param tag_name: The name of a markup tag. - """ - if self.empty_element_tags is None: - return True - return tag_name in self.empty_element_tags - - def feed(self, markup): - """Run some incoming markup through some parsing process, - populating the `BeautifulSoup` object in self.soup. - - This method is not implemented in TreeBuilder; it must be - implemented in subclasses. - - :return: None. - """ - raise NotImplementedError() - - def prepare_markup(self, markup, user_specified_encoding=None, - document_declared_encoding=None, exclude_encodings=None): - """Run any preliminary steps necessary to make incoming markup - acceptable to the parser. - - :param markup: Some markup -- probably a bytestring. - :param user_specified_encoding: The user asked to try this encoding. - :param document_declared_encoding: The markup itself claims to be - in this encoding. - :param exclude_encodings: The user asked _not_ to try any of - these encodings. - - :yield: A series of 4-tuples: - (markup, encoding, declared encoding, - has undergone character replacement) - - Each 4-tuple represents a strategy for converting the - document to Unicode and parsing it. Each strategy will be tried - in turn. - - By default, the only strategy is to parse the markup - as-is. See `LXMLTreeBuilderForXML` and - `HTMLParserTreeBuilder` for implementations that take into - account the quirks of particular parsers. - """ - yield markup, None, None, False - - def test_fragment_to_document(self, fragment): - """Wrap an HTML fragment to make it look like a document. - - Different parsers do this differently. For instance, lxml - introduces an empty tag, and html5lib - doesn't. Abstracting this away lets us write simple tests - which run HTML fragments through the parser and compare the - results against other HTML fragments. - - This method should not be used outside of tests. - - :param fragment: A string -- fragment of HTML. - :return: A string -- a full HTML document. - """ - return fragment - - def set_up_substitutions(self, tag): - """Set up any substitutions that will need to be performed on - a `Tag` when it's output as a string. - - By default, this does nothing. See `HTMLTreeBuilder` for a - case where this is used. - - :param tag: A `Tag` - :return: Whether or not a substitution was performed. - """ - return False - - def _replace_cdata_list_attribute_values(self, tag_name, attrs): - """When an attribute value is associated with a tag that can - have multiple values for that attribute, convert the string - value to a list of strings. - - Basically, replaces class="foo bar" with class=["foo", "bar"] - - NOTE: This method modifies its input in place. - - :param tag_name: The name of a tag. - :param attrs: A dictionary containing the tag's attributes. - Any appropriate attribute values will be modified in place. - """ - if not attrs: - return attrs - if self.cdata_list_attributes: - universal = self.cdata_list_attributes.get('*', []) - tag_specific = self.cdata_list_attributes.get( - tag_name.lower(), None) - for attr in list(attrs.keys()): - if attr in universal or (tag_specific and attr in tag_specific): - # We have a "class"-type attribute whose string - # value is a whitespace-separated list of - # values. Split it into a list. - value = attrs[attr] - if isinstance(value, str): - values = nonwhitespace_re.findall(value) - else: - # html5lib sometimes calls setAttributes twice - # for the same tag when rearranging the parse - # tree. On the second call the attribute value - # here is already a list. If this happens, - # leave the value alone rather than trying to - # split it again. - values = value - attrs[attr] = values - return attrs - -class SAXTreeBuilder(TreeBuilder): - """A Beautiful Soup treebuilder that listens for SAX events. - - This is not currently used for anything, but it demonstrates - how a simple TreeBuilder would work. - """ - - def feed(self, markup): - raise NotImplementedError() - - def close(self): - pass - - def startElement(self, name, attrs): - attrs = dict((key[1], value) for key, value in list(attrs.items())) - #print("Start %s, %r" % (name, attrs)) - self.soup.handle_starttag(name, attrs) - - def endElement(self, name): - #print("End %s" % name) - self.soup.handle_endtag(name) - - def startElementNS(self, nsTuple, nodeName, attrs): - # Throw away (ns, nodeName) for now. - self.startElement(nodeName, attrs) - - def endElementNS(self, nsTuple, nodeName): - # Throw away (ns, nodeName) for now. - self.endElement(nodeName) - #handler.endElementNS((ns, node.nodeName), node.nodeName) - - def startPrefixMapping(self, prefix, nodeValue): - # Ignore the prefix for now. - pass - - def endPrefixMapping(self, prefix): - # Ignore the prefix for now. - # handler.endPrefixMapping(prefix) - pass - - def characters(self, content): - self.soup.handle_data(content) - - def startDocument(self): - pass - - def endDocument(self): - pass - - -class HTMLTreeBuilder(TreeBuilder): - """This TreeBuilder knows facts about HTML. - - Such as which tags are empty-element tags. - """ - - empty_element_tags = set([ - # These are from HTML5. - 'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'keygen', 'link', 'menuitem', 'meta', 'param', 'source', 'track', 'wbr', - - # These are from earlier versions of HTML and are removed in HTML5. - 'basefont', 'bgsound', 'command', 'frame', 'image', 'isindex', 'nextid', 'spacer' - ]) - - # The HTML standard defines these as block-level elements. Beautiful - # Soup does not treat these elements differently from other elements, - # but it may do so eventually, and this information is available if - # you need to use it. - block_elements = set(["address", "article", "aside", "blockquote", "canvas", "dd", "div", "dl", "dt", "fieldset", "figcaption", "figure", "footer", "form", "h1", "h2", "h3", "h4", "h5", "h6", "header", "hr", "li", "main", "nav", "noscript", "ol", "output", "p", "pre", "section", "table", "tfoot", "ul", "video"]) - - # The HTML standard defines an unusual content model for these tags. - # We represent this by using a string class other than NavigableString - # inside these tags. - # - # I made this list by going through the HTML spec - # (https://html.spec.whatwg.org/#metadata-content) and looking for - # "metadata content" elements that can contain strings. - # - # TODO: Arguably

as a -# string. -# -# XXX This code can be removed once most Python 3 users are on 3.2.3. -if major == 3 and minor == 2 and not CONSTRUCTOR_TAKES_STRICT: - import re - attrfind_tolerant = re.compile( - r'\s*((?<=[\'"\s])[^\s/>][^\s/=>]*)(\s*=+\s*' - r'(\'[^\']*\'|"[^"]*"|(?![\'"])[^>\s]*))?') - HTMLParserTreeBuilder.attrfind_tolerant = attrfind_tolerant - - locatestarttagend = re.compile(r""" - <[a-zA-Z][-.a-zA-Z0-9:_]* # tag name - (?:\s+ # whitespace before attribute name - (?:[a-zA-Z_][-.:a-zA-Z0-9_]* # attribute name - (?:\s*=\s* # value indicator - (?:'[^']*' # LITA-enclosed value - |\"[^\"]*\" # LIT-enclosed value - |[^'\">\s]+ # bare value - ) - )? - ) - )* - \s* # trailing whitespace -""", re.VERBOSE) - BeautifulSoupHTMLParser.locatestarttagend = locatestarttagend - - from html.parser import tagfind, attrfind - - def parse_starttag(self, i): - self.__starttag_text = None - endpos = self.check_for_whole_start_tag(i) - if endpos < 0: - return endpos - rawdata = self.rawdata - self.__starttag_text = rawdata[i:endpos] - - # Now parse the data between i+1 and j into a tag and attrs - attrs = [] - match = tagfind.match(rawdata, i+1) - assert match, 'unexpected call to parse_starttag()' - k = match.end() - self.lasttag = tag = rawdata[i+1:k].lower() - while k < endpos: - if self.strict: - m = attrfind.match(rawdata, k) - else: - m = attrfind_tolerant.match(rawdata, k) - if not m: - break - attrname, rest, attrvalue = m.group(1, 2, 3) - if not rest: - attrvalue = None - elif attrvalue[:1] == '\'' == attrvalue[-1:] or \ - attrvalue[:1] == '"' == attrvalue[-1:]: - attrvalue = attrvalue[1:-1] - if attrvalue: - attrvalue = self.unescape(attrvalue) - attrs.append((attrname.lower(), attrvalue)) - k = m.end() - - end = rawdata[k:endpos].strip() - if end not in (">", "/>"): - lineno, offset = self.getpos() - if "\n" in self.__starttag_text: - lineno = lineno + self.__starttag_text.count("\n") - offset = len(self.__starttag_text) \ - - self.__starttag_text.rfind("\n") - else: - offset = offset + len(self.__starttag_text) - if self.strict: - self.error("junk characters in start tag: %r" - % (rawdata[k:endpos][:20],)) - self.handle_data(rawdata[i:endpos]) - return endpos - if end.endswith('/>'): - # XHTML-style empty tag: - self.handle_startendtag(tag, attrs) - else: - self.handle_starttag(tag, attrs) - if tag in self.CDATA_CONTENT_ELEMENTS: - self.set_cdata_mode(tag) - return endpos - - def set_cdata_mode(self, elem): - self.cdata_elem = elem.lower() - self.interesting = re.compile(r'' % self.cdata_elem, re.I) - - BeautifulSoupHTMLParser.parse_starttag = parse_starttag - BeautifulSoupHTMLParser.set_cdata_mode = set_cdata_mode - - CONSTRUCTOR_TAKES_STRICT = True diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4/builder/_lxml.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4/builder/_lxml.py deleted file mode 100644 index 432a2c8..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4/builder/_lxml.py +++ /dev/null @@ -1,332 +0,0 @@ -# Use of this source code is governed by the MIT license. -__license__ = "MIT" - -__all__ = [ - 'LXMLTreeBuilderForXML', - 'LXMLTreeBuilder', - ] - -try: - from collections.abc import Callable # Python 3.6 -except ImportError as e: - from collections import Callable - -from io import BytesIO -from io import StringIO -from lxml import etree -from bs4.element import ( - Comment, - Doctype, - NamespacedAttribute, - ProcessingInstruction, - XMLProcessingInstruction, -) -from bs4.builder import ( - FAST, - HTML, - HTMLTreeBuilder, - PERMISSIVE, - ParserRejectedMarkup, - TreeBuilder, - XML) -from bs4.dammit import EncodingDetector - -LXML = 'lxml' - -def _invert(d): - "Invert a dictionary." - return dict((v,k) for k, v in list(d.items())) - -class LXMLTreeBuilderForXML(TreeBuilder): - DEFAULT_PARSER_CLASS = etree.XMLParser - - is_xml = True - processing_instruction_class = XMLProcessingInstruction - - NAME = "lxml-xml" - ALTERNATE_NAMES = ["xml"] - - # Well, it's permissive by XML parser standards. - features = [NAME, LXML, XML, FAST, PERMISSIVE] - - CHUNK_SIZE = 512 - - # This namespace mapping is specified in the XML Namespace - # standard. - DEFAULT_NSMAPS = dict(xml='http://www.w3.org/XML/1998/namespace') - - DEFAULT_NSMAPS_INVERTED = _invert(DEFAULT_NSMAPS) - - # NOTE: If we parsed Element objects and looked at .sourceline, - # we'd be able to see the line numbers from the original document. - # But instead we build an XMLParser or HTMLParser object to serve - # as the target of parse messages, and those messages don't include - # line numbers. - # See: https://bugs.launchpad.net/lxml/+bug/1846906 - - def initialize_soup(self, soup): - """Let the BeautifulSoup object know about the standard namespace - mapping. - - :param soup: A `BeautifulSoup`. - """ - super(LXMLTreeBuilderForXML, self).initialize_soup(soup) - self._register_namespaces(self.DEFAULT_NSMAPS) - - def _register_namespaces(self, mapping): - """Let the BeautifulSoup object know about namespaces encountered - while parsing the document. - - This might be useful later on when creating CSS selectors. - - :param mapping: A dictionary mapping namespace prefixes to URIs. - """ - for key, value in list(mapping.items()): - if key and key not in self.soup._namespaces: - # Let the BeautifulSoup object know about a new namespace. - # If there are multiple namespaces defined with the same - # prefix, the first one in the document takes precedence. - self.soup._namespaces[key] = value - - def default_parser(self, encoding): - """Find the default parser for the given encoding. - - :param encoding: A string. - :return: Either a parser object or a class, which - will be instantiated with default arguments. - """ - if self._default_parser is not None: - return self._default_parser - return etree.XMLParser( - target=self, strip_cdata=False, recover=True, encoding=encoding) - - def parser_for(self, encoding): - """Instantiate an appropriate parser for the given encoding. - - :param encoding: A string. - :return: A parser object such as an `etree.XMLParser`. - """ - # Use the default parser. - parser = self.default_parser(encoding) - - if isinstance(parser, Callable): - # Instantiate the parser with default arguments - parser = parser( - target=self, strip_cdata=False, recover=True, encoding=encoding - ) - return parser - - def __init__(self, parser=None, empty_element_tags=None, **kwargs): - # TODO: Issue a warning if parser is present but not a - # callable, since that means there's no way to create new - # parsers for different encodings. - self._default_parser = parser - if empty_element_tags is not None: - self.empty_element_tags = set(empty_element_tags) - self.soup = None - self.nsmaps = [self.DEFAULT_NSMAPS_INVERTED] - super(LXMLTreeBuilderForXML, self).__init__(**kwargs) - - def _getNsTag(self, tag): - # Split the namespace URL out of a fully-qualified lxml tag - # name. Copied from lxml's src/lxml/sax.py. - if tag[0] == '{': - return tuple(tag[1:].split('}', 1)) - else: - return (None, tag) - - def prepare_markup(self, markup, user_specified_encoding=None, - exclude_encodings=None, - document_declared_encoding=None): - """Run any preliminary steps necessary to make incoming markup - acceptable to the parser. - - lxml really wants to get a bytestring and convert it to - Unicode itself. So instead of using UnicodeDammit to convert - the bytestring to Unicode using different encodings, this - implementation uses EncodingDetector to iterate over the - encodings, and tell lxml to try to parse the document as each - one in turn. - - :param markup: Some markup -- hopefully a bytestring. - :param user_specified_encoding: The user asked to try this encoding. - :param document_declared_encoding: The markup itself claims to be - in this encoding. - :param exclude_encodings: The user asked _not_ to try any of - these encodings. - - :yield: A series of 4-tuples: - (markup, encoding, declared encoding, - has undergone character replacement) - - Each 4-tuple represents a strategy for converting the - document to Unicode and parsing it. Each strategy will be tried - in turn. - """ - is_html = not self.is_xml - if is_html: - self.processing_instruction_class = ProcessingInstruction - else: - self.processing_instruction_class = XMLProcessingInstruction - - if isinstance(markup, str): - # We were given Unicode. Maybe lxml can parse Unicode on - # this system? - yield markup, None, document_declared_encoding, False - - if isinstance(markup, str): - # No, apparently not. Convert the Unicode to UTF-8 and - # tell lxml to parse it as UTF-8. - yield (markup.encode("utf8"), "utf8", - document_declared_encoding, False) - - try_encodings = [user_specified_encoding, document_declared_encoding] - detector = EncodingDetector( - markup, try_encodings, is_html, exclude_encodings) - for encoding in detector.encodings: - yield (detector.markup, encoding, document_declared_encoding, False) - - def feed(self, markup): - if isinstance(markup, bytes): - markup = BytesIO(markup) - elif isinstance(markup, str): - markup = StringIO(markup) - - # Call feed() at least once, even if the markup is empty, - # or the parser won't be initialized. - data = markup.read(self.CHUNK_SIZE) - try: - self.parser = self.parser_for(self.soup.original_encoding) - self.parser.feed(data) - while len(data) != 0: - # Now call feed() on the rest of the data, chunk by chunk. - data = markup.read(self.CHUNK_SIZE) - if len(data) != 0: - self.parser.feed(data) - self.parser.close() - except (UnicodeDecodeError, LookupError, etree.ParserError) as e: - raise ParserRejectedMarkup(e) - - def close(self): - self.nsmaps = [self.DEFAULT_NSMAPS_INVERTED] - - def start(self, name, attrs, nsmap={}): - # Make sure attrs is a mutable dict--lxml may send an immutable dictproxy. - attrs = dict(attrs) - nsprefix = None - # Invert each namespace map as it comes in. - if len(nsmap) == 0 and len(self.nsmaps) > 1: - # There are no new namespaces for this tag, but - # non-default namespaces are in play, so we need a - # separate tag stack to know when they end. - self.nsmaps.append(None) - elif len(nsmap) > 0: - # A new namespace mapping has come into play. - - # First, Let the BeautifulSoup object know about it. - self._register_namespaces(nsmap) - - # Then, add it to our running list of inverted namespace - # mappings. - self.nsmaps.append(_invert(nsmap)) - - # Also treat the namespace mapping as a set of attributes on the - # tag, so we can recreate it later. - attrs = attrs.copy() - for prefix, namespace in list(nsmap.items()): - attribute = NamespacedAttribute( - "xmlns", prefix, "http://www.w3.org/2000/xmlns/") - attrs[attribute] = namespace - - # Namespaces are in play. Find any attributes that came in - # from lxml with namespaces attached to their names, and - # turn then into NamespacedAttribute objects. - new_attrs = {} - for attr, value in list(attrs.items()): - namespace, attr = self._getNsTag(attr) - if namespace is None: - new_attrs[attr] = value - else: - nsprefix = self._prefix_for_namespace(namespace) - attr = NamespacedAttribute(nsprefix, attr, namespace) - new_attrs[attr] = value - attrs = new_attrs - - namespace, name = self._getNsTag(name) - nsprefix = self._prefix_for_namespace(namespace) - self.soup.handle_starttag(name, namespace, nsprefix, attrs) - - def _prefix_for_namespace(self, namespace): - """Find the currently active prefix for the given namespace.""" - if namespace is None: - return None - for inverted_nsmap in reversed(self.nsmaps): - if inverted_nsmap is not None and namespace in inverted_nsmap: - return inverted_nsmap[namespace] - return None - - def end(self, name): - self.soup.endData() - completed_tag = self.soup.tagStack[-1] - namespace, name = self._getNsTag(name) - nsprefix = None - if namespace is not None: - for inverted_nsmap in reversed(self.nsmaps): - if inverted_nsmap is not None and namespace in inverted_nsmap: - nsprefix = inverted_nsmap[namespace] - break - self.soup.handle_endtag(name, nsprefix) - if len(self.nsmaps) > 1: - # This tag, or one of its parents, introduced a namespace - # mapping, so pop it off the stack. - self.nsmaps.pop() - - def pi(self, target, data): - self.soup.endData() - self.soup.handle_data(target + ' ' + data) - self.soup.endData(self.processing_instruction_class) - - def data(self, content): - self.soup.handle_data(content) - - def doctype(self, name, pubid, system): - self.soup.endData() - doctype = Doctype.for_name_and_ids(name, pubid, system) - self.soup.object_was_parsed(doctype) - - def comment(self, content): - "Handle comments as Comment objects." - self.soup.endData() - self.soup.handle_data(content) - self.soup.endData(Comment) - - def test_fragment_to_document(self, fragment): - """See `TreeBuilder`.""" - return '\n%s' % fragment - - -class LXMLTreeBuilder(HTMLTreeBuilder, LXMLTreeBuilderForXML): - - NAME = LXML - ALTERNATE_NAMES = ["lxml-html"] - - features = ALTERNATE_NAMES + [NAME, HTML, FAST, PERMISSIVE] - is_xml = False - processing_instruction_class = ProcessingInstruction - - def default_parser(self, encoding): - return etree.HTMLParser - - def feed(self, markup): - encoding = self.soup.original_encoding - try: - self.parser = self.parser_for(encoding) - self.parser.feed(markup) - self.parser.close() - except (UnicodeDecodeError, LookupError, etree.ParserError) as e: - raise ParserRejectedMarkup(e) - - - def test_fragment_to_document(self, fragment): - """See `TreeBuilder`.""" - return '%s' % fragment diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4/dammit.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4/dammit.py deleted file mode 100644 index ee3708f..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4/dammit.py +++ /dev/null @@ -1,939 +0,0 @@ -# -*- coding: utf-8 -*- -"""Beautiful Soup bonus library: Unicode, Dammit - -This library converts a bytestream to Unicode through any means -necessary. It is heavily based on code from Mark Pilgrim's Universal -Feed Parser. It works best on XML and HTML, but it does not rewrite the -XML or HTML to reflect a new encoding; that's the tree builder's job. -""" -# Use of this source code is governed by the MIT license. -__license__ = "MIT" - -import codecs -from html.entities import codepoint2name -import re -import logging -import string - -# Import a library to autodetect character encodings. -chardet_type = None -try: - # First try the fast C implementation. - # PyPI package: cchardet - import cchardet - def chardet_dammit(s): - if isinstance(s, str): - return None - return cchardet.detect(s)['encoding'] -except ImportError: - try: - # Fall back to the pure Python implementation - # Debian package: python-chardet - # PyPI package: chardet - import chardet - def chardet_dammit(s): - if isinstance(s, str): - return None - return chardet.detect(s)['encoding'] - #import chardet.constants - #chardet.constants._debug = 1 - except ImportError: - # No chardet available. - def chardet_dammit(s): - return None - -# Available from http://cjkpython.i18n.org/. -# -# TODO: This doesn't work anymore and the closest thing, iconv_codecs, -# is GPL-licensed. Check whether this is still necessary. -try: - import iconv_codec -except ImportError: - pass - -# Build bytestring and Unicode versions of regular expressions for finding -# a declared encoding inside an XML or HTML document. -xml_encoding = '^\\s*<\\?.*encoding=[\'"](.*?)[\'"].*\\?>' -html_meta = '<\\s*meta[^>]+charset\\s*=\\s*["\']?([^>]*?)[ /;\'">]' -encoding_res = dict() -encoding_res[bytes] = { - 'html' : re.compile(html_meta.encode("ascii"), re.I), - 'xml' : re.compile(xml_encoding.encode("ascii"), re.I), -} -encoding_res[str] = { - 'html' : re.compile(html_meta, re.I), - 'xml' : re.compile(xml_encoding, re.I) -} - -class EntitySubstitution(object): - """The ability to substitute XML or HTML entities for certain characters.""" - - def _populate_class_variables(): - lookup = {} - reverse_lookup = {} - characters_for_re = [] - - # &apos is an XHTML entity and an HTML 5, but not an HTML 4 - # entity. We don't want to use it, but we want to recognize it on the way in. - # - # TODO: Ideally we would be able to recognize all HTML 5 named - # entities, but that's a little tricky. - extra = [(39, 'apos')] - for codepoint, name in list(codepoint2name.items()) + extra: - character = chr(codepoint) - if codepoint not in (34, 39): - # There's no point in turning the quotation mark into - # " or the single quote into ', unless it - # happens within an attribute value, which is handled - # elsewhere. - characters_for_re.append(character) - lookup[character] = name - # But we do want to recognize those entities on the way in and - # convert them to Unicode characters. - reverse_lookup[name] = character - re_definition = "[%s]" % "".join(characters_for_re) - return lookup, reverse_lookup, re.compile(re_definition) - (CHARACTER_TO_HTML_ENTITY, HTML_ENTITY_TO_CHARACTER, - CHARACTER_TO_HTML_ENTITY_RE) = _populate_class_variables() - - CHARACTER_TO_XML_ENTITY = { - "'": "apos", - '"': "quot", - "&": "amp", - "<": "lt", - ">": "gt", - } - - BARE_AMPERSAND_OR_BRACKET = re.compile("([<>]|" - "&(?!#\\d+;|#x[0-9a-fA-F]+;|\\w+;)" - ")") - - AMPERSAND_OR_BRACKET = re.compile("([<>&])") - - @classmethod - def _substitute_html_entity(cls, matchobj): - """Used with a regular expression to substitute the - appropriate HTML entity for a special character.""" - entity = cls.CHARACTER_TO_HTML_ENTITY.get(matchobj.group(0)) - return "&%s;" % entity - - @classmethod - def _substitute_xml_entity(cls, matchobj): - """Used with a regular expression to substitute the - appropriate XML entity for a special character.""" - entity = cls.CHARACTER_TO_XML_ENTITY[matchobj.group(0)] - return "&%s;" % entity - - @classmethod - def quoted_attribute_value(self, value): - """Make a value into a quoted XML attribute, possibly escaping it. - - Most strings will be quoted using double quotes. - - Bob's Bar -> "Bob's Bar" - - If a string contains double quotes, it will be quoted using - single quotes. - - Welcome to "my bar" -> 'Welcome to "my bar"' - - If a string contains both single and double quotes, the - double quotes will be escaped, and the string will be quoted - using double quotes. - - Welcome to "Bob's Bar" -> "Welcome to "Bob's bar" - """ - quote_with = '"' - if '"' in value: - if "'" in value: - # The string contains both single and double - # quotes. Turn the double quotes into - # entities. We quote the double quotes rather than - # the single quotes because the entity name is - # """ whether this is HTML or XML. If we - # quoted the single quotes, we'd have to decide - # between ' and &squot;. - replace_with = """ - value = value.replace('"', replace_with) - else: - # There are double quotes but no single quotes. - # We can use single quotes to quote the attribute. - quote_with = "'" - return quote_with + value + quote_with - - @classmethod - def substitute_xml(cls, value, make_quoted_attribute=False): - """Substitute XML entities for special XML characters. - - :param value: A string to be substituted. The less-than sign - will become <, the greater-than sign will become >, - and any ampersands will become &. If you want ampersands - that appear to be part of an entity definition to be left - alone, use substitute_xml_containing_entities() instead. - - :param make_quoted_attribute: If True, then the string will be - quoted, as befits an attribute value. - """ - # Escape angle brackets and ampersands. - value = cls.AMPERSAND_OR_BRACKET.sub( - cls._substitute_xml_entity, value) - - if make_quoted_attribute: - value = cls.quoted_attribute_value(value) - return value - - @classmethod - def substitute_xml_containing_entities( - cls, value, make_quoted_attribute=False): - """Substitute XML entities for special XML characters. - - :param value: A string to be substituted. The less-than sign will - become <, the greater-than sign will become >, and any - ampersands that are not part of an entity defition will - become &. - - :param make_quoted_attribute: If True, then the string will be - quoted, as befits an attribute value. - """ - # Escape angle brackets, and ampersands that aren't part of - # entities. - value = cls.BARE_AMPERSAND_OR_BRACKET.sub( - cls._substitute_xml_entity, value) - - if make_quoted_attribute: - value = cls.quoted_attribute_value(value) - return value - - @classmethod - def substitute_html(cls, s): - """Replace certain Unicode characters with named HTML entities. - - This differs from data.encode(encoding, 'xmlcharrefreplace') - in that the goal is to make the result more readable (to those - with ASCII displays) rather than to recover from - errors. There's absolutely nothing wrong with a UTF-8 string - containg a LATIN SMALL LETTER E WITH ACUTE, but replacing that - character with "é" will make it more readable to some - people. - - :param s: A Unicode string. - """ - return cls.CHARACTER_TO_HTML_ENTITY_RE.sub( - cls._substitute_html_entity, s) - - -class EncodingDetector: - """Suggests a number of possible encodings for a bytestring. - - Order of precedence: - - 1. Encodings you specifically tell EncodingDetector to try first - (the override_encodings argument to the constructor). - - 2. An encoding declared within the bytestring itself, either in an - XML declaration (if the bytestring is to be interpreted as an XML - document), or in a tag (if the bytestring is to be - interpreted as an HTML document.) - - 3. An encoding detected through textual analysis by chardet, - cchardet, or a similar external library. - - 4. UTF-8. - - 5. Windows-1252. - """ - def __init__(self, markup, override_encodings=None, is_html=False, - exclude_encodings=None): - """Constructor. - - :param markup: Some markup in an unknown encoding. - :param override_encodings: These encodings will be tried first. - :param is_html: If True, this markup is considered to be HTML. Otherwise - it's assumed to be XML. - :param exclude_encodings: These encodings will not be tried, even - if they otherwise would be. - """ - self.override_encodings = override_encodings or [] - exclude_encodings = exclude_encodings or [] - self.exclude_encodings = set([x.lower() for x in exclude_encodings]) - self.chardet_encoding = None - self.is_html = is_html - self.declared_encoding = None - - # First order of business: strip a byte-order mark. - self.markup, self.sniffed_encoding = self.strip_byte_order_mark(markup) - - def _usable(self, encoding, tried): - """Should we even bother to try this encoding? - - :param encoding: Name of an encoding. - :param tried: Encodings that have already been tried. This will be modified - as a side effect. - """ - if encoding is not None: - encoding = encoding.lower() - if encoding in self.exclude_encodings: - return False - if encoding not in tried: - tried.add(encoding) - return True - return False - - @property - def encodings(self): - """Yield a number of encodings that might work for this markup. - - :yield: A sequence of strings. - """ - tried = set() - for e in self.override_encodings: - if self._usable(e, tried): - yield e - - # Did the document originally start with a byte-order mark - # that indicated its encoding? - if self._usable(self.sniffed_encoding, tried): - yield self.sniffed_encoding - - # Look within the document for an XML or HTML encoding - # declaration. - if self.declared_encoding is None: - self.declared_encoding = self.find_declared_encoding( - self.markup, self.is_html) - if self._usable(self.declared_encoding, tried): - yield self.declared_encoding - - # Use third-party character set detection to guess at the - # encoding. - if self.chardet_encoding is None: - self.chardet_encoding = chardet_dammit(self.markup) - if self._usable(self.chardet_encoding, tried): - yield self.chardet_encoding - - # As a last-ditch effort, try utf-8 and windows-1252. - for e in ('utf-8', 'windows-1252'): - if self._usable(e, tried): - yield e - - @classmethod - def strip_byte_order_mark(cls, data): - """If a byte-order mark is present, strip it and return the encoding it implies. - - :param data: Some markup. - :return: A 2-tuple (modified data, implied encoding) - """ - encoding = None - if isinstance(data, str): - # Unicode data cannot have a byte-order mark. - return data, encoding - if (len(data) >= 4) and (data[:2] == b'\xfe\xff') \ - and (data[2:4] != '\x00\x00'): - encoding = 'utf-16be' - data = data[2:] - elif (len(data) >= 4) and (data[:2] == b'\xff\xfe') \ - and (data[2:4] != '\x00\x00'): - encoding = 'utf-16le' - data = data[2:] - elif data[:3] == b'\xef\xbb\xbf': - encoding = 'utf-8' - data = data[3:] - elif data[:4] == b'\x00\x00\xfe\xff': - encoding = 'utf-32be' - data = data[4:] - elif data[:4] == b'\xff\xfe\x00\x00': - encoding = 'utf-32le' - data = data[4:] - return data, encoding - - @classmethod - def find_declared_encoding(cls, markup, is_html=False, search_entire_document=False): - """Given a document, tries to find its declared encoding. - - An XML encoding is declared at the beginning of the document. - - An HTML encoding is declared in a tag, hopefully near the - beginning of the document. - - :param markup: Some markup. - :param is_html: If True, this markup is considered to be HTML. Otherwise - it's assumed to be XML. - :param search_entire_document: Since an encoding is supposed to declared near the beginning - of the document, most of the time it's only necessary to search a few kilobytes of data. - Set this to True to force this method to search the entire document. - """ - if search_entire_document: - xml_endpos = html_endpos = len(markup) - else: - xml_endpos = 1024 - html_endpos = max(2048, int(len(markup) * 0.05)) - - if isinstance(markup, bytes): - res = encoding_res[bytes] - else: - res = encoding_res[str] - - xml_re = res['xml'] - html_re = res['html'] - declared_encoding = None - declared_encoding_match = xml_re.search(markup, endpos=xml_endpos) - if not declared_encoding_match and is_html: - declared_encoding_match = html_re.search(markup, endpos=html_endpos) - if declared_encoding_match is not None: - declared_encoding = declared_encoding_match.groups()[0] - if declared_encoding: - if isinstance(declared_encoding, bytes): - declared_encoding = declared_encoding.decode('ascii', 'replace') - return declared_encoding.lower() - return None - -class UnicodeDammit: - """A class for detecting the encoding of a *ML document and - converting it to a Unicode string. If the source encoding is - windows-1252, can replace MS smart quotes with their HTML or XML - equivalents.""" - - # This dictionary maps commonly seen values for "charset" in HTML - # meta tags to the corresponding Python codec names. It only covers - # values that aren't in Python's aliases and can't be determined - # by the heuristics in find_codec. - CHARSET_ALIASES = {"macintosh": "mac-roman", - "x-sjis": "shift-jis"} - - ENCODINGS_WITH_SMART_QUOTES = [ - "windows-1252", - "iso-8859-1", - "iso-8859-2", - ] - - def __init__(self, markup, override_encodings=[], - smart_quotes_to=None, is_html=False, exclude_encodings=[]): - """Constructor. - - :param markup: A bytestring representing markup in an unknown encoding. - :param override_encodings: These encodings will be tried first, - before any sniffing code is run. - - :param smart_quotes_to: By default, Microsoft smart quotes will, like all other characters, be converted - to Unicode characters. Setting this to 'ascii' will convert them to ASCII quotes instead. - Setting it to 'xml' will convert them to XML entity references, and setting it to 'html' - will convert them to HTML entity references. - :param is_html: If True, this markup is considered to be HTML. Otherwise - it's assumed to be XML. - :param exclude_encodings: These encodings will not be considered, even - if the sniffing code thinks they might make sense. - """ - self.smart_quotes_to = smart_quotes_to - self.tried_encodings = [] - self.contains_replacement_characters = False - self.is_html = is_html - self.log = logging.getLogger(__name__) - self.detector = EncodingDetector( - markup, override_encodings, is_html, exclude_encodings) - - # Short-circuit if the data is in Unicode to begin with. - if isinstance(markup, str) or markup == '': - self.markup = markup - self.unicode_markup = str(markup) - self.original_encoding = None - return - - # The encoding detector may have stripped a byte-order mark. - # Use the stripped markup from this point on. - self.markup = self.detector.markup - - u = None - for encoding in self.detector.encodings: - markup = self.detector.markup - u = self._convert_from(encoding) - if u is not None: - break - - if not u: - # None of the encodings worked. As an absolute last resort, - # try them again with character replacement. - - for encoding in self.detector.encodings: - if encoding != "ascii": - u = self._convert_from(encoding, "replace") - if u is not None: - self.log.warning( - "Some characters could not be decoded, and were " - "replaced with REPLACEMENT CHARACTER." - ) - self.contains_replacement_characters = True - break - - # If none of that worked, we could at this point force it to - # ASCII, but that would destroy so much data that I think - # giving up is better. - self.unicode_markup = u - if not u: - self.original_encoding = None - - def _sub_ms_char(self, match): - """Changes a MS smart quote character to an XML or HTML - entity, or an ASCII character.""" - orig = match.group(1) - if self.smart_quotes_to == 'ascii': - sub = self.MS_CHARS_TO_ASCII.get(orig).encode() - else: - sub = self.MS_CHARS.get(orig) - if type(sub) == tuple: - if self.smart_quotes_to == 'xml': - sub = '&#x'.encode() + sub[1].encode() + ';'.encode() - else: - sub = '&'.encode() + sub[0].encode() + ';'.encode() - else: - sub = sub.encode() - return sub - - def _convert_from(self, proposed, errors="strict"): - """Attempt to convert the markup to the proposed encoding. - - :param proposed: The name of a character encoding. - """ - proposed = self.find_codec(proposed) - if not proposed or (proposed, errors) in self.tried_encodings: - return None - self.tried_encodings.append((proposed, errors)) - markup = self.markup - # Convert smart quotes to HTML if coming from an encoding - # that might have them. - if (self.smart_quotes_to is not None - and proposed in self.ENCODINGS_WITH_SMART_QUOTES): - smart_quotes_re = b"([\x80-\x9f])" - smart_quotes_compiled = re.compile(smart_quotes_re) - markup = smart_quotes_compiled.sub(self._sub_ms_char, markup) - - try: - #print("Trying to convert document to %s (errors=%s)" % ( - # proposed, errors)) - u = self._to_unicode(markup, proposed, errors) - self.markup = u - self.original_encoding = proposed - except Exception as e: - #print("That didn't work!") - #print(e) - return None - #print("Correct encoding: %s" % proposed) - return self.markup - - def _to_unicode(self, data, encoding, errors="strict"): - """Given a string and its encoding, decodes the string into Unicode. - - :param encoding: The name of an encoding. - """ - return str(data, encoding, errors) - - @property - def declared_html_encoding(self): - """If the markup is an HTML document, returns the encoding declared _within_ - the document. - """ - if not self.is_html: - return None - return self.detector.declared_encoding - - def find_codec(self, charset): - """Convert the name of a character set to a codec name. - - :param charset: The name of a character set. - :return: The name of a codec. - """ - value = (self._codec(self.CHARSET_ALIASES.get(charset, charset)) - or (charset and self._codec(charset.replace("-", ""))) - or (charset and self._codec(charset.replace("-", "_"))) - or (charset and charset.lower()) - or charset - ) - if value: - return value.lower() - return None - - def _codec(self, charset): - if not charset: - return charset - codec = None - try: - codecs.lookup(charset) - codec = charset - except (LookupError, ValueError): - pass - return codec - - - # A partial mapping of ISO-Latin-1 to HTML entities/XML numeric entities. - MS_CHARS = {b'\x80': ('euro', '20AC'), - b'\x81': ' ', - b'\x82': ('sbquo', '201A'), - b'\x83': ('fnof', '192'), - b'\x84': ('bdquo', '201E'), - b'\x85': ('hellip', '2026'), - b'\x86': ('dagger', '2020'), - b'\x87': ('Dagger', '2021'), - b'\x88': ('circ', '2C6'), - b'\x89': ('permil', '2030'), - b'\x8A': ('Scaron', '160'), - b'\x8B': ('lsaquo', '2039'), - b'\x8C': ('OElig', '152'), - b'\x8D': '?', - b'\x8E': ('#x17D', '17D'), - b'\x8F': '?', - b'\x90': '?', - b'\x91': ('lsquo', '2018'), - b'\x92': ('rsquo', '2019'), - b'\x93': ('ldquo', '201C'), - b'\x94': ('rdquo', '201D'), - b'\x95': ('bull', '2022'), - b'\x96': ('ndash', '2013'), - b'\x97': ('mdash', '2014'), - b'\x98': ('tilde', '2DC'), - b'\x99': ('trade', '2122'), - b'\x9a': ('scaron', '161'), - b'\x9b': ('rsaquo', '203A'), - b'\x9c': ('oelig', '153'), - b'\x9d': '?', - b'\x9e': ('#x17E', '17E'), - b'\x9f': ('Yuml', ''),} - - # A parochial partial mapping of ISO-Latin-1 to ASCII. Contains - # horrors like stripping diacritical marks to turn á into a, but also - # contains non-horrors like turning “ into ". - MS_CHARS_TO_ASCII = { - b'\x80' : 'EUR', - b'\x81' : ' ', - b'\x82' : ',', - b'\x83' : 'f', - b'\x84' : ',,', - b'\x85' : '...', - b'\x86' : '+', - b'\x87' : '++', - b'\x88' : '^', - b'\x89' : '%', - b'\x8a' : 'S', - b'\x8b' : '<', - b'\x8c' : 'OE', - b'\x8d' : '?', - b'\x8e' : 'Z', - b'\x8f' : '?', - b'\x90' : '?', - b'\x91' : "'", - b'\x92' : "'", - b'\x93' : '"', - b'\x94' : '"', - b'\x95' : '*', - b'\x96' : '-', - b'\x97' : '--', - b'\x98' : '~', - b'\x99' : '(TM)', - b'\x9a' : 's', - b'\x9b' : '>', - b'\x9c' : 'oe', - b'\x9d' : '?', - b'\x9e' : 'z', - b'\x9f' : 'Y', - b'\xa0' : ' ', - b'\xa1' : '!', - b'\xa2' : 'c', - b'\xa3' : 'GBP', - b'\xa4' : '$', #This approximation is especially parochial--this is the - #generic currency symbol. - b'\xa5' : 'YEN', - b'\xa6' : '|', - b'\xa7' : 'S', - b'\xa8' : '..', - b'\xa9' : '', - b'\xaa' : '(th)', - b'\xab' : '<<', - b'\xac' : '!', - b'\xad' : ' ', - b'\xae' : '(R)', - b'\xaf' : '-', - b'\xb0' : 'o', - b'\xb1' : '+-', - b'\xb2' : '2', - b'\xb3' : '3', - b'\xb4' : ("'", 'acute'), - b'\xb5' : 'u', - b'\xb6' : 'P', - b'\xb7' : '*', - b'\xb8' : ',', - b'\xb9' : '1', - b'\xba' : '(th)', - b'\xbb' : '>>', - b'\xbc' : '1/4', - b'\xbd' : '1/2', - b'\xbe' : '3/4', - b'\xbf' : '?', - b'\xc0' : 'A', - b'\xc1' : 'A', - b'\xc2' : 'A', - b'\xc3' : 'A', - b'\xc4' : 'A', - b'\xc5' : 'A', - b'\xc6' : 'AE', - b'\xc7' : 'C', - b'\xc8' : 'E', - b'\xc9' : 'E', - b'\xca' : 'E', - b'\xcb' : 'E', - b'\xcc' : 'I', - b'\xcd' : 'I', - b'\xce' : 'I', - b'\xcf' : 'I', - b'\xd0' : 'D', - b'\xd1' : 'N', - b'\xd2' : 'O', - b'\xd3' : 'O', - b'\xd4' : 'O', - b'\xd5' : 'O', - b'\xd6' : 'O', - b'\xd7' : '*', - b'\xd8' : 'O', - b'\xd9' : 'U', - b'\xda' : 'U', - b'\xdb' : 'U', - b'\xdc' : 'U', - b'\xdd' : 'Y', - b'\xde' : 'b', - b'\xdf' : 'B', - b'\xe0' : 'a', - b'\xe1' : 'a', - b'\xe2' : 'a', - b'\xe3' : 'a', - b'\xe4' : 'a', - b'\xe5' : 'a', - b'\xe6' : 'ae', - b'\xe7' : 'c', - b'\xe8' : 'e', - b'\xe9' : 'e', - b'\xea' : 'e', - b'\xeb' : 'e', - b'\xec' : 'i', - b'\xed' : 'i', - b'\xee' : 'i', - b'\xef' : 'i', - b'\xf0' : 'o', - b'\xf1' : 'n', - b'\xf2' : 'o', - b'\xf3' : 'o', - b'\xf4' : 'o', - b'\xf5' : 'o', - b'\xf6' : 'o', - b'\xf7' : '/', - b'\xf8' : 'o', - b'\xf9' : 'u', - b'\xfa' : 'u', - b'\xfb' : 'u', - b'\xfc' : 'u', - b'\xfd' : 'y', - b'\xfe' : 'b', - b'\xff' : 'y', - } - - # A map used when removing rogue Windows-1252/ISO-8859-1 - # characters in otherwise UTF-8 documents. - # - # Note that \x81, \x8d, \x8f, \x90, and \x9d are undefined in - # Windows-1252. - WINDOWS_1252_TO_UTF8 = { - 0x80 : b'\xe2\x82\xac', # € - 0x82 : b'\xe2\x80\x9a', # ‚ - 0x83 : b'\xc6\x92', # ƒ - 0x84 : b'\xe2\x80\x9e', # „ - 0x85 : b'\xe2\x80\xa6', # … - 0x86 : b'\xe2\x80\xa0', # † - 0x87 : b'\xe2\x80\xa1', # ‡ - 0x88 : b'\xcb\x86', # ˆ - 0x89 : b'\xe2\x80\xb0', # ‰ - 0x8a : b'\xc5\xa0', # Š - 0x8b : b'\xe2\x80\xb9', # ‹ - 0x8c : b'\xc5\x92', # Œ - 0x8e : b'\xc5\xbd', # Ž - 0x91 : b'\xe2\x80\x98', # ‘ - 0x92 : b'\xe2\x80\x99', # ’ - 0x93 : b'\xe2\x80\x9c', # “ - 0x94 : b'\xe2\x80\x9d', # ” - 0x95 : b'\xe2\x80\xa2', # • - 0x96 : b'\xe2\x80\x93', # – - 0x97 : b'\xe2\x80\x94', # — - 0x98 : b'\xcb\x9c', # ˜ - 0x99 : b'\xe2\x84\xa2', # ™ - 0x9a : b'\xc5\xa1', # š - 0x9b : b'\xe2\x80\xba', # › - 0x9c : b'\xc5\x93', # œ - 0x9e : b'\xc5\xbe', # ž - 0x9f : b'\xc5\xb8', # Ÿ - 0xa0 : b'\xc2\xa0', #   - 0xa1 : b'\xc2\xa1', # ¡ - 0xa2 : b'\xc2\xa2', # ¢ - 0xa3 : b'\xc2\xa3', # £ - 0xa4 : b'\xc2\xa4', # ¤ - 0xa5 : b'\xc2\xa5', # ¥ - 0xa6 : b'\xc2\xa6', # ¦ - 0xa7 : b'\xc2\xa7', # § - 0xa8 : b'\xc2\xa8', # ¨ - 0xa9 : b'\xc2\xa9', # © - 0xaa : b'\xc2\xaa', # ª - 0xab : b'\xc2\xab', # « - 0xac : b'\xc2\xac', # ¬ - 0xad : b'\xc2\xad', # ­ - 0xae : b'\xc2\xae', # ® - 0xaf : b'\xc2\xaf', # ¯ - 0xb0 : b'\xc2\xb0', # ° - 0xb1 : b'\xc2\xb1', # ± - 0xb2 : b'\xc2\xb2', # ² - 0xb3 : b'\xc2\xb3', # ³ - 0xb4 : b'\xc2\xb4', # ´ - 0xb5 : b'\xc2\xb5', # µ - 0xb6 : b'\xc2\xb6', # ¶ - 0xb7 : b'\xc2\xb7', # · - 0xb8 : b'\xc2\xb8', # ¸ - 0xb9 : b'\xc2\xb9', # ¹ - 0xba : b'\xc2\xba', # º - 0xbb : b'\xc2\xbb', # » - 0xbc : b'\xc2\xbc', # ¼ - 0xbd : b'\xc2\xbd', # ½ - 0xbe : b'\xc2\xbe', # ¾ - 0xbf : b'\xc2\xbf', # ¿ - 0xc0 : b'\xc3\x80', # À - 0xc1 : b'\xc3\x81', # Á - 0xc2 : b'\xc3\x82', #  - 0xc3 : b'\xc3\x83', # à - 0xc4 : b'\xc3\x84', # Ä - 0xc5 : b'\xc3\x85', # Å - 0xc6 : b'\xc3\x86', # Æ - 0xc7 : b'\xc3\x87', # Ç - 0xc8 : b'\xc3\x88', # È - 0xc9 : b'\xc3\x89', # É - 0xca : b'\xc3\x8a', # Ê - 0xcb : b'\xc3\x8b', # Ë - 0xcc : b'\xc3\x8c', # Ì - 0xcd : b'\xc3\x8d', # Í - 0xce : b'\xc3\x8e', # Î - 0xcf : b'\xc3\x8f', # Ï - 0xd0 : b'\xc3\x90', # Ð - 0xd1 : b'\xc3\x91', # Ñ - 0xd2 : b'\xc3\x92', # Ò - 0xd3 : b'\xc3\x93', # Ó - 0xd4 : b'\xc3\x94', # Ô - 0xd5 : b'\xc3\x95', # Õ - 0xd6 : b'\xc3\x96', # Ö - 0xd7 : b'\xc3\x97', # × - 0xd8 : b'\xc3\x98', # Ø - 0xd9 : b'\xc3\x99', # Ù - 0xda : b'\xc3\x9a', # Ú - 0xdb : b'\xc3\x9b', # Û - 0xdc : b'\xc3\x9c', # Ü - 0xdd : b'\xc3\x9d', # Ý - 0xde : b'\xc3\x9e', # Þ - 0xdf : b'\xc3\x9f', # ß - 0xe0 : b'\xc3\xa0', # à - 0xe1 : b'\xa1', # á - 0xe2 : b'\xc3\xa2', # â - 0xe3 : b'\xc3\xa3', # ã - 0xe4 : b'\xc3\xa4', # ä - 0xe5 : b'\xc3\xa5', # å - 0xe6 : b'\xc3\xa6', # æ - 0xe7 : b'\xc3\xa7', # ç - 0xe8 : b'\xc3\xa8', # è - 0xe9 : b'\xc3\xa9', # é - 0xea : b'\xc3\xaa', # ê - 0xeb : b'\xc3\xab', # ë - 0xec : b'\xc3\xac', # ì - 0xed : b'\xc3\xad', # í - 0xee : b'\xc3\xae', # î - 0xef : b'\xc3\xaf', # ï - 0xf0 : b'\xc3\xb0', # ð - 0xf1 : b'\xc3\xb1', # ñ - 0xf2 : b'\xc3\xb2', # ò - 0xf3 : b'\xc3\xb3', # ó - 0xf4 : b'\xc3\xb4', # ô - 0xf5 : b'\xc3\xb5', # õ - 0xf6 : b'\xc3\xb6', # ö - 0xf7 : b'\xc3\xb7', # ÷ - 0xf8 : b'\xc3\xb8', # ø - 0xf9 : b'\xc3\xb9', # ù - 0xfa : b'\xc3\xba', # ú - 0xfb : b'\xc3\xbb', # û - 0xfc : b'\xc3\xbc', # ü - 0xfd : b'\xc3\xbd', # ý - 0xfe : b'\xc3\xbe', # þ - } - - MULTIBYTE_MARKERS_AND_SIZES = [ - (0xc2, 0xdf, 2), # 2-byte characters start with a byte C2-DF - (0xe0, 0xef, 3), # 3-byte characters start with E0-EF - (0xf0, 0xf4, 4), # 4-byte characters start with F0-F4 - ] - - FIRST_MULTIBYTE_MARKER = MULTIBYTE_MARKERS_AND_SIZES[0][0] - LAST_MULTIBYTE_MARKER = MULTIBYTE_MARKERS_AND_SIZES[-1][1] - - @classmethod - def detwingle(cls, in_bytes, main_encoding="utf8", - embedded_encoding="windows-1252"): - """Fix characters from one encoding embedded in some other encoding. - - Currently the only situation supported is Windows-1252 (or its - subset ISO-8859-1), embedded in UTF-8. - - :param in_bytes: A bytestring that you suspect contains - characters from multiple encodings. Note that this _must_ - be a bytestring. If you've already converted the document - to Unicode, you're too late. - :param main_encoding: The primary encoding of `in_bytes`. - :param embedded_encoding: The encoding that was used to embed characters - in the main document. - :return: A bytestring in which `embedded_encoding` - characters have been converted to their `main_encoding` - equivalents. - """ - if embedded_encoding.replace('_', '-').lower() not in ( - 'windows-1252', 'windows_1252'): - raise NotImplementedError( - "Windows-1252 and ISO-8859-1 are the only currently supported " - "embedded encodings.") - - if main_encoding.lower() not in ('utf8', 'utf-8'): - raise NotImplementedError( - "UTF-8 is the only currently supported main encoding.") - - byte_chunks = [] - - chunk_start = 0 - pos = 0 - while pos < len(in_bytes): - byte = in_bytes[pos] - if not isinstance(byte, int): - # Python 2.x - byte = ord(byte) - if (byte >= cls.FIRST_MULTIBYTE_MARKER - and byte <= cls.LAST_MULTIBYTE_MARKER): - # This is the start of a UTF-8 multibyte character. Skip - # to the end. - for start, end, size in cls.MULTIBYTE_MARKERS_AND_SIZES: - if byte >= start and byte <= end: - pos += size - break - elif byte >= 0x80 and byte in cls.WINDOWS_1252_TO_UTF8: - # We found a Windows-1252 character! - # Save the string up to this point as a chunk. - byte_chunks.append(in_bytes[chunk_start:pos]) - - # Now translate the Windows-1252 character into UTF-8 - # and add it as another, one-byte chunk. - byte_chunks.append(cls.WINDOWS_1252_TO_UTF8[byte]) - pos += 1 - chunk_start = pos - else: - # Go on to the next character. - pos += 1 - if chunk_start == 0: - # The string is unchanged. - return in_bytes - else: - # Store the final chunk. - byte_chunks.append(in_bytes[chunk_start:]) - return b''.join(byte_chunks) - diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4/diagnose.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4/diagnose.py deleted file mode 100644 index 1877acd..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4/diagnose.py +++ /dev/null @@ -1,242 +0,0 @@ -"""Diagnostic functions, mainly for use when doing tech support.""" - -# Use of this source code is governed by the MIT license. -__license__ = "MIT" - -import cProfile -from io import StringIO -from html.parser import HTMLParser -import bs4 -from bs4 import BeautifulSoup, __version__ -from bs4.builder import builder_registry - -import os -import pstats -import random -import tempfile -import time -import traceback -import sys -import cProfile - -def diagnose(data): - """Diagnostic suite for isolating common problems. - - :param data: A string containing markup that needs to be explained. - :return: None; diagnostics are printed to standard output. - """ - print(("Diagnostic running on Beautiful Soup %s" % __version__)) - print(("Python version %s" % sys.version)) - - basic_parsers = ["html.parser", "html5lib", "lxml"] - for name in basic_parsers: - for builder in builder_registry.builders: - if name in builder.features: - break - else: - basic_parsers.remove(name) - print(( - "I noticed that %s is not installed. Installing it may help." % - name)) - - if 'lxml' in basic_parsers: - basic_parsers.append("lxml-xml") - try: - from lxml import etree - print(("Found lxml version %s" % ".".join(map(str,etree.LXML_VERSION)))) - except ImportError as e: - print( - "lxml is not installed or couldn't be imported.") - - - if 'html5lib' in basic_parsers: - try: - import html5lib - print(("Found html5lib version %s" % html5lib.__version__)) - except ImportError as e: - print( - "html5lib is not installed or couldn't be imported.") - - if hasattr(data, 'read'): - data = data.read() - elif data.startswith("http:") or data.startswith("https:"): - print(('"%s" looks like a URL. Beautiful Soup is not an HTTP client.' % data)) - print("You need to use some other library to get the document behind the URL, and feed that document to Beautiful Soup.") - return - else: - try: - if os.path.exists(data): - print(('"%s" looks like a filename. Reading data from the file.' % data)) - with open(data) as fp: - data = fp.read() - except ValueError: - # This can happen on some platforms when the 'filename' is - # too long. Assume it's data and not a filename. - pass - print("") - - for parser in basic_parsers: - print(("Trying to parse your markup with %s" % parser)) - success = False - try: - soup = BeautifulSoup(data, features=parser) - success = True - except Exception as e: - print(("%s could not parse the markup." % parser)) - traceback.print_exc() - if success: - print(("Here's what %s did with the markup:" % parser)) - print((soup.prettify())) - - print(("-" * 80)) - -def lxml_trace(data, html=True, **kwargs): - """Print out the lxml events that occur during parsing. - - This lets you see how lxml parses a document when no Beautiful - Soup code is running. You can use this to determine whether - an lxml-specific problem is in Beautiful Soup's lxml tree builders - or in lxml itself. - - :param data: Some markup. - :param html: If True, markup will be parsed with lxml's HTML parser. - if False, lxml's XML parser will be used. - """ - from lxml import etree - for event, element in etree.iterparse(StringIO(data), html=html, **kwargs): - print(("%s, %4s, %s" % (event, element.tag, element.text))) - -class AnnouncingParser(HTMLParser): - """Subclass of HTMLParser that announces parse events, without doing - anything else. - - You can use this to get a picture of how html.parser sees a given - document. The easiest way to do this is to call `htmlparser_trace`. - """ - - def _p(self, s): - print(s) - - def handle_starttag(self, name, attrs): - self._p("%s START" % name) - - def handle_endtag(self, name): - self._p("%s END" % name) - - def handle_data(self, data): - self._p("%s DATA" % data) - - def handle_charref(self, name): - self._p("%s CHARREF" % name) - - def handle_entityref(self, name): - self._p("%s ENTITYREF" % name) - - def handle_comment(self, data): - self._p("%s COMMENT" % data) - - def handle_decl(self, data): - self._p("%s DECL" % data) - - def unknown_decl(self, data): - self._p("%s UNKNOWN-DECL" % data) - - def handle_pi(self, data): - self._p("%s PI" % data) - -def htmlparser_trace(data): - """Print out the HTMLParser events that occur during parsing. - - This lets you see how HTMLParser parses a document when no - Beautiful Soup code is running. - - :param data: Some markup. - """ - parser = AnnouncingParser() - parser.feed(data) - -_vowels = "aeiou" -_consonants = "bcdfghjklmnpqrstvwxyz" - -def rword(length=5): - "Generate a random word-like string." - s = '' - for i in range(length): - if i % 2 == 0: - t = _consonants - else: - t = _vowels - s += random.choice(t) - return s - -def rsentence(length=4): - "Generate a random sentence-like string." - return " ".join(rword(random.randint(4,9)) for i in list(range(length))) - -def rdoc(num_elements=1000): - """Randomly generate an invalid HTML document.""" - tag_names = ['p', 'div', 'span', 'i', 'b', 'script', 'table'] - elements = [] - for i in range(num_elements): - choice = random.randint(0,3) - if choice == 0: - # New tag. - tag_name = random.choice(tag_names) - elements.append("<%s>" % tag_name) - elif choice == 1: - elements.append(rsentence(random.randint(1,4))) - elif choice == 2: - # Close a tag. - tag_name = random.choice(tag_names) - elements.append("" % tag_name) - return "" + "\n".join(elements) + "" - -def benchmark_parsers(num_elements=100000): - """Very basic head-to-head performance benchmark.""" - print(("Comparative parser benchmark on Beautiful Soup %s" % __version__)) - data = rdoc(num_elements) - print(("Generated a large invalid HTML document (%d bytes)." % len(data))) - - for parser in ["lxml", ["lxml", "html"], "html5lib", "html.parser"]: - success = False - try: - a = time.time() - soup = BeautifulSoup(data, parser) - b = time.time() - success = True - except Exception as e: - print(("%s could not parse the markup." % parser)) - traceback.print_exc() - if success: - print(("BS4+%s parsed the markup in %.2fs." % (parser, b-a))) - - from lxml import etree - a = time.time() - etree.HTML(data) - b = time.time() - print(("Raw lxml parsed the markup in %.2fs." % (b-a))) - - import html5lib - parser = html5lib.HTMLParser() - a = time.time() - parser.parse(data) - b = time.time() - print(("Raw html5lib parsed the markup in %.2fs." % (b-a))) - -def profile(num_elements=100000, parser="lxml"): - """Use Python's profiler on a randomly generated document.""" - filehandle = tempfile.NamedTemporaryFile() - filename = filehandle.name - - data = rdoc(num_elements) - vars = dict(bs4=bs4, data=data, parser=parser) - cProfile.runctx('bs4.BeautifulSoup(data, parser)' , vars, vars, filename) - - stats = pstats.Stats(filename) - # stats.strip_dirs() - stats.sort_stats("cumulative") - stats.print_stats('_html5lib|bs4', 50) - -# If this file is run as a script, standard input is diagnosed. -if __name__ == '__main__': - diagnose(sys.stdin.read()) diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4/element.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4/element.py deleted file mode 100644 index c7dc650..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4/element.py +++ /dev/null @@ -1,2162 +0,0 @@ -# Use of this source code is governed by the MIT license. -__license__ = "MIT" - -try: - from collections.abc import Callable # Python 3.6 -except ImportError as e: - from collections import Callable -import re -import sys -import warnings -try: - import soupsieve -except ImportError as e: - soupsieve = None - warnings.warn( - 'The soupsieve package is not installed. CSS selectors cannot be used.' - ) - -from bs4.formatter import ( - Formatter, - HTMLFormatter, - XMLFormatter, -) - -DEFAULT_OUTPUT_ENCODING = "utf-8" -PY3K = (sys.version_info[0] > 2) - -nonwhitespace_re = re.compile(r"\S+") - -# NOTE: This isn't used as of 4.7.0. I'm leaving it for a little bit on -# the off chance someone imported it for their own use. -whitespace_re = re.compile(r"\s+") - -def _alias(attr): - """Alias one attribute name to another for backward compatibility""" - @property - def alias(self): - return getattr(self, attr) - - @alias.setter - def alias(self): - return setattr(self, attr) - return alias - - -# These encodings are recognized by Python (so PageElement.encode -# could theoretically support them) but XML and HTML don't recognize -# them (so they should not show up in an XML or HTML document as that -# document's encoding). -# -# If an XML document is encoded in one of these encodings, no encoding -# will be mentioned in the XML declaration. If an HTML document is -# encoded in one of these encodings, and the HTML document has a -# tag that mentions an encoding, the encoding will be given as -# the empty string. -# -# Source: -# https://docs.python.org/3/library/codecs.html#python-specific-encodings -PYTHON_SPECIFIC_ENCODINGS = set([ - "idna", - "mbcs", - "oem", - "palmos", - "punycode", - "raw_unicode_escape", - "undefined", - "unicode_escape", - "raw-unicode-escape", - "unicode-escape", - "string-escape", - "string_escape", -]) - - -class NamespacedAttribute(str): - """A namespaced string (e.g. 'xml:lang') that remembers the namespace - ('xml') and the name ('lang') that were used to create it. - """ - - def __new__(cls, prefix, name=None, namespace=None): - if not name: - # This is the default namespace. Its name "has no value" - # per https://www.w3.org/TR/xml-names/#defaulting - name = None - - if name is None: - obj = str.__new__(cls, prefix) - elif prefix is None: - # Not really namespaced. - obj = str.__new__(cls, name) - else: - obj = str.__new__(cls, prefix + ":" + name) - obj.prefix = prefix - obj.name = name - obj.namespace = namespace - return obj - -class AttributeValueWithCharsetSubstitution(str): - """A stand-in object for a character encoding specified in HTML.""" - -class CharsetMetaAttributeValue(AttributeValueWithCharsetSubstitution): - """A generic stand-in for the value of a meta tag's 'charset' attribute. - - When Beautiful Soup parses the markup '', the - value of the 'charset' attribute will be one of these objects. - """ - - def __new__(cls, original_value): - obj = str.__new__(cls, original_value) - obj.original_value = original_value - return obj - - def encode(self, encoding): - """When an HTML document is being encoded to a given encoding, the - value of a meta tag's 'charset' is the name of the encoding. - """ - if encoding in PYTHON_SPECIFIC_ENCODINGS: - return '' - return encoding - - -class ContentMetaAttributeValue(AttributeValueWithCharsetSubstitution): - """A generic stand-in for the value of a meta tag's 'content' attribute. - - When Beautiful Soup parses the markup: - - - The value of the 'content' attribute will be one of these objects. - """ - - CHARSET_RE = re.compile(r"((^|;)\s*charset=)([^;]*)", re.M) - - def __new__(cls, original_value): - match = cls.CHARSET_RE.search(original_value) - if match is None: - # No substitution necessary. - return str.__new__(str, original_value) - - obj = str.__new__(cls, original_value) - obj.original_value = original_value - return obj - - def encode(self, encoding): - if encoding in PYTHON_SPECIFIC_ENCODINGS: - return '' - def rewrite(match): - return match.group(1) + encoding - return self.CHARSET_RE.sub(rewrite, self.original_value) - - -class PageElement(object): - """Contains the navigational information for some part of the page: - that is, its current location in the parse tree. - - NavigableString, Tag, etc. are all subclasses of PageElement. - """ - - def setup(self, parent=None, previous_element=None, next_element=None, - previous_sibling=None, next_sibling=None): - """Sets up the initial relations between this element and - other elements. - - :param parent: The parent of this element. - - :param previous_element: The element parsed immediately before - this one. - - :param next_element: The element parsed immediately before - this one. - - :param previous_sibling: The most recently encountered element - on the same level of the parse tree as this one. - - :param previous_sibling: The next element to be encountered - on the same level of the parse tree as this one. - """ - self.parent = parent - - self.previous_element = previous_element - if previous_element is not None: - self.previous_element.next_element = self - - self.next_element = next_element - if self.next_element is not None: - self.next_element.previous_element = self - - self.next_sibling = next_sibling - if self.next_sibling is not None: - self.next_sibling.previous_sibling = self - - if (previous_sibling is None - and self.parent is not None and self.parent.contents): - previous_sibling = self.parent.contents[-1] - - self.previous_sibling = previous_sibling - if previous_sibling is not None: - self.previous_sibling.next_sibling = self - - def format_string(self, s, formatter): - """Format the given string using the given formatter. - - :param s: A string. - :param formatter: A Formatter object, or a string naming one of the standard formatters. - """ - if formatter is None: - return s - if not isinstance(formatter, Formatter): - formatter = self.formatter_for_name(formatter) - output = formatter.substitute(s) - return output - - def formatter_for_name(self, formatter): - """Look up or create a Formatter for the given identifier, - if necessary. - - :param formatter: Can be a Formatter object (used as-is), a - function (used as the entity substitution hook for an - XMLFormatter or HTMLFormatter), or a string (used to look - up an XMLFormatter or HTMLFormatter in the appropriate - registry. - """ - if isinstance(formatter, Formatter): - return formatter - if self._is_xml: - c = XMLFormatter - else: - c = HTMLFormatter - if isinstance(formatter, Callable): - return c(entity_substitution=formatter) - return c.REGISTRY[formatter] - - @property - def _is_xml(self): - """Is this element part of an XML tree or an HTML tree? - - This is used in formatter_for_name, when deciding whether an - XMLFormatter or HTMLFormatter is more appropriate. It can be - inefficient, but it should be called very rarely. - """ - if self.known_xml is not None: - # Most of the time we will have determined this when the - # document is parsed. - return self.known_xml - - # Otherwise, it's likely that this element was created by - # direct invocation of the constructor from within the user's - # Python code. - if self.parent is None: - # This is the top-level object. It should have .known_xml set - # from tree creation. If not, take a guess--BS is usually - # used on HTML markup. - return getattr(self, 'is_xml', False) - return self.parent._is_xml - - nextSibling = _alias("next_sibling") # BS3 - previousSibling = _alias("previous_sibling") # BS3 - - def replace_with(self, replace_with): - """Replace this PageElement with another one, keeping the rest of the - tree the same. - - :param replace_with: A PageElement. - :return: `self`, no longer part of the tree. - """ - if self.parent is None: - raise ValueError( - "Cannot replace one element with another when the " - "element to be replaced is not part of a tree.") - if replace_with is self: - return - if replace_with is self.parent: - raise ValueError("Cannot replace a Tag with its parent.") - old_parent = self.parent - my_index = self.parent.index(self) - self.extract(_self_index=my_index) - old_parent.insert(my_index, replace_with) - return self - replaceWith = replace_with # BS3 - - def unwrap(self): - """Replace this PageElement with its contents. - - :return: `self`, no longer part of the tree. - """ - my_parent = self.parent - if self.parent is None: - raise ValueError( - "Cannot replace an element with its contents when that" - "element is not part of a tree.") - my_index = self.parent.index(self) - self.extract(_self_index=my_index) - for child in reversed(self.contents[:]): - my_parent.insert(my_index, child) - return self - replace_with_children = unwrap - replaceWithChildren = unwrap # BS3 - - def wrap(self, wrap_inside): - """Wrap this PageElement inside another one. - - :param wrap_inside: A PageElement. - :return: `wrap_inside`, occupying the position in the tree that used - to be occupied by `self`, and with `self` inside it. - """ - me = self.replace_with(wrap_inside) - wrap_inside.append(me) - return wrap_inside - - def extract(self, _self_index=None): - """Destructively rips this element out of the tree. - - :param _self_index: The location of this element in its parent's - .contents, if known. Passing this in allows for a performance - optimization. - - :return: `self`, no longer part of the tree. - """ - if self.parent is not None: - if _self_index is None: - _self_index = self.parent.index(self) - del self.parent.contents[_self_index] - - #Find the two elements that would be next to each other if - #this element (and any children) hadn't been parsed. Connect - #the two. - last_child = self._last_descendant() - next_element = last_child.next_element - - if (self.previous_element is not None and - self.previous_element is not next_element): - self.previous_element.next_element = next_element - if next_element is not None and next_element is not self.previous_element: - next_element.previous_element = self.previous_element - self.previous_element = None - last_child.next_element = None - - self.parent = None - if (self.previous_sibling is not None - and self.previous_sibling is not self.next_sibling): - self.previous_sibling.next_sibling = self.next_sibling - if (self.next_sibling is not None - and self.next_sibling is not self.previous_sibling): - self.next_sibling.previous_sibling = self.previous_sibling - self.previous_sibling = self.next_sibling = None - return self - - def _last_descendant(self, is_initialized=True, accept_self=True): - """Finds the last element beneath this object to be parsed. - - :param is_initialized: Has `setup` been called on this PageElement - yet? - :param accept_self: Is `self` an acceptable answer to the question? - """ - if is_initialized and self.next_sibling is not None: - last_child = self.next_sibling.previous_element - else: - last_child = self - while isinstance(last_child, Tag) and last_child.contents: - last_child = last_child.contents[-1] - if not accept_self and last_child is self: - last_child = None - return last_child - # BS3: Not part of the API! - _lastRecursiveChild = _last_descendant - - def insert(self, position, new_child): - """Insert a new PageElement in the list of this PageElement's children. - - This works the same way as `list.insert`. - - :param position: The numeric position that should be occupied - in `self.children` by the new PageElement. - :param new_child: A PageElement. - """ - if new_child is None: - raise ValueError("Cannot insert None into a tag.") - if new_child is self: - raise ValueError("Cannot insert a tag into itself.") - if (isinstance(new_child, str) - and not isinstance(new_child, NavigableString)): - new_child = NavigableString(new_child) - - from bs4 import BeautifulSoup - if isinstance(new_child, BeautifulSoup): - # We don't want to end up with a situation where one BeautifulSoup - # object contains another. Insert the children one at a time. - for subchild in list(new_child.contents): - self.insert(position, subchild) - position += 1 - return - position = min(position, len(self.contents)) - if hasattr(new_child, 'parent') and new_child.parent is not None: - # We're 'inserting' an element that's already one - # of this object's children. - if new_child.parent is self: - current_index = self.index(new_child) - if current_index < position: - # We're moving this element further down the list - # of this object's children. That means that when - # we extract this element, our target index will - # jump down one. - position -= 1 - new_child.extract() - - new_child.parent = self - previous_child = None - if position == 0: - new_child.previous_sibling = None - new_child.previous_element = self - else: - previous_child = self.contents[position - 1] - new_child.previous_sibling = previous_child - new_child.previous_sibling.next_sibling = new_child - new_child.previous_element = previous_child._last_descendant(False) - if new_child.previous_element is not None: - new_child.previous_element.next_element = new_child - - new_childs_last_element = new_child._last_descendant(False) - - if position >= len(self.contents): - new_child.next_sibling = None - - parent = self - parents_next_sibling = None - while parents_next_sibling is None and parent is not None: - parents_next_sibling = parent.next_sibling - parent = parent.parent - if parents_next_sibling is not None: - # We found the element that comes next in the document. - break - if parents_next_sibling is not None: - new_childs_last_element.next_element = parents_next_sibling - else: - # The last element of this tag is the last element in - # the document. - new_childs_last_element.next_element = None - else: - next_child = self.contents[position] - new_child.next_sibling = next_child - if new_child.next_sibling is not None: - new_child.next_sibling.previous_sibling = new_child - new_childs_last_element.next_element = next_child - - if new_childs_last_element.next_element is not None: - new_childs_last_element.next_element.previous_element = new_childs_last_element - self.contents.insert(position, new_child) - - def append(self, tag): - """Appends the given PageElement to the contents of this one. - - :param tag: A PageElement. - """ - self.insert(len(self.contents), tag) - - def extend(self, tags): - """Appends the given PageElements to this one's contents. - - :param tags: A list of PageElements. - """ - for tag in tags: - self.append(tag) - - def insert_before(self, *args): - """Makes the given element(s) the immediate predecessor of this one. - - All the elements will have the same parent, and the given elements - will be immediately before this one. - - :param args: One or more PageElements. - """ - parent = self.parent - if parent is None: - raise ValueError( - "Element has no parent, so 'before' has no meaning.") - if any(x is self for x in args): - raise ValueError("Can't insert an element before itself.") - for predecessor in args: - # Extract first so that the index won't be screwed up if they - # are siblings. - if isinstance(predecessor, PageElement): - predecessor.extract() - index = parent.index(self) - parent.insert(index, predecessor) - - def insert_after(self, *args): - """Makes the given element(s) the immediate successor of this one. - - The elements will have the same parent, and the given elements - will be immediately after this one. - - :param args: One or more PageElements. - """ - # Do all error checking before modifying the tree. - parent = self.parent - if parent is None: - raise ValueError( - "Element has no parent, so 'after' has no meaning.") - if any(x is self for x in args): - raise ValueError("Can't insert an element after itself.") - - offset = 0 - for successor in args: - # Extract first so that the index won't be screwed up if they - # are siblings. - if isinstance(successor, PageElement): - successor.extract() - index = parent.index(self) - parent.insert(index+1+offset, successor) - offset += 1 - - def find_next(self, name=None, attrs={}, text=None, **kwargs): - """Find the first PageElement that matches the given criteria and - appears later in the document than this PageElement. - - All find_* methods take a common set of arguments. See the online - documentation for detailed explanations. - - :param name: A filter on tag name. - :param attrs: A dictionary of filters on attribute values. - :param text: A filter for a NavigableString with specific text. - :kwargs: A dictionary of filters on attribute values. - :return: A PageElement. - :rtype: bs4.element.Tag | bs4.element.NavigableString - """ - return self._find_one(self.find_all_next, name, attrs, text, **kwargs) - findNext = find_next # BS3 - - def find_all_next(self, name=None, attrs={}, text=None, limit=None, - **kwargs): - """Find all PageElements that match the given criteria and appear - later in the document than this PageElement. - - All find_* methods take a common set of arguments. See the online - documentation for detailed explanations. - - :param name: A filter on tag name. - :param attrs: A dictionary of filters on attribute values. - :param text: A filter for a NavigableString with specific text. - :param limit: Stop looking after finding this many results. - :kwargs: A dictionary of filters on attribute values. - :return: A ResultSet containing PageElements. - """ - return self._find_all(name, attrs, text, limit, self.next_elements, - **kwargs) - findAllNext = find_all_next # BS3 - - def find_next_sibling(self, name=None, attrs={}, text=None, **kwargs): - """Find the closest sibling to this PageElement that matches the - given criteria and appears later in the document. - - All find_* methods take a common set of arguments. See the - online documentation for detailed explanations. - - :param name: A filter on tag name. - :param attrs: A dictionary of filters on attribute values. - :param text: A filter for a NavigableString with specific text. - :kwargs: A dictionary of filters on attribute values. - :return: A PageElement. - :rtype: bs4.element.Tag | bs4.element.NavigableString - """ - return self._find_one(self.find_next_siblings, name, attrs, text, - **kwargs) - findNextSibling = find_next_sibling # BS3 - - def find_next_siblings(self, name=None, attrs={}, text=None, limit=None, - **kwargs): - """Find all siblings of this PageElement that match the given criteria - and appear later in the document. - - All find_* methods take a common set of arguments. See the online - documentation for detailed explanations. - - :param name: A filter on tag name. - :param attrs: A dictionary of filters on attribute values. - :param text: A filter for a NavigableString with specific text. - :param limit: Stop looking after finding this many results. - :kwargs: A dictionary of filters on attribute values. - :return: A ResultSet of PageElements. - :rtype: bs4.element.ResultSet - """ - return self._find_all(name, attrs, text, limit, - self.next_siblings, **kwargs) - findNextSiblings = find_next_siblings # BS3 - fetchNextSiblings = find_next_siblings # BS2 - - def find_previous(self, name=None, attrs={}, text=None, **kwargs): - """Look backwards in the document from this PageElement and find the - first PageElement that matches the given criteria. - - All find_* methods take a common set of arguments. See the online - documentation for detailed explanations. - - :param name: A filter on tag name. - :param attrs: A dictionary of filters on attribute values. - :param text: A filter for a NavigableString with specific text. - :kwargs: A dictionary of filters on attribute values. - :return: A PageElement. - :rtype: bs4.element.Tag | bs4.element.NavigableString - """ - return self._find_one( - self.find_all_previous, name, attrs, text, **kwargs) - findPrevious = find_previous # BS3 - - def find_all_previous(self, name=None, attrs={}, text=None, limit=None, - **kwargs): - """Look backwards in the document from this PageElement and find all - PageElements that match the given criteria. - - All find_* methods take a common set of arguments. See the online - documentation for detailed explanations. - - :param name: A filter on tag name. - :param attrs: A dictionary of filters on attribute values. - :param text: A filter for a NavigableString with specific text. - :param limit: Stop looking after finding this many results. - :kwargs: A dictionary of filters on attribute values. - :return: A ResultSet of PageElements. - :rtype: bs4.element.ResultSet - """ - return self._find_all(name, attrs, text, limit, self.previous_elements, - **kwargs) - findAllPrevious = find_all_previous # BS3 - fetchPrevious = find_all_previous # BS2 - - def find_previous_sibling(self, name=None, attrs={}, text=None, **kwargs): - """Returns the closest sibling to this PageElement that matches the - given criteria and appears earlier in the document. - - All find_* methods take a common set of arguments. See the online - documentation for detailed explanations. - - :param name: A filter on tag name. - :param attrs: A dictionary of filters on attribute values. - :param text: A filter for a NavigableString with specific text. - :kwargs: A dictionary of filters on attribute values. - :return: A PageElement. - :rtype: bs4.element.Tag | bs4.element.NavigableString - """ - return self._find_one(self.find_previous_siblings, name, attrs, text, - **kwargs) - findPreviousSibling = find_previous_sibling # BS3 - - def find_previous_siblings(self, name=None, attrs={}, text=None, - limit=None, **kwargs): - """Returns all siblings to this PageElement that match the - given criteria and appear earlier in the document. - - All find_* methods take a common set of arguments. See the online - documentation for detailed explanations. - - :param name: A filter on tag name. - :param attrs: A dictionary of filters on attribute values. - :param text: A filter for a NavigableString with specific text. - :param limit: Stop looking after finding this many results. - :kwargs: A dictionary of filters on attribute values. - :return: A ResultSet of PageElements. - :rtype: bs4.element.ResultSet - """ - return self._find_all(name, attrs, text, limit, - self.previous_siblings, **kwargs) - findPreviousSiblings = find_previous_siblings # BS3 - fetchPreviousSiblings = find_previous_siblings # BS2 - - def find_parent(self, name=None, attrs={}, **kwargs): - """Find the closest parent of this PageElement that matches the given - criteria. - - All find_* methods take a common set of arguments. See the online - documentation for detailed explanations. - - :param name: A filter on tag name. - :param attrs: A dictionary of filters on attribute values. - :kwargs: A dictionary of filters on attribute values. - - :return: A PageElement. - :rtype: bs4.element.Tag | bs4.element.NavigableString - """ - # NOTE: We can't use _find_one because findParents takes a different - # set of arguments. - r = None - l = self.find_parents(name, attrs, 1, **kwargs) - if l: - r = l[0] - return r - findParent = find_parent # BS3 - - def find_parents(self, name=None, attrs={}, limit=None, **kwargs): - """Find all parents of this PageElement that match the given criteria. - - All find_* methods take a common set of arguments. See the online - documentation for detailed explanations. - - :param name: A filter on tag name. - :param attrs: A dictionary of filters on attribute values. - :param limit: Stop looking after finding this many results. - :kwargs: A dictionary of filters on attribute values. - - :return: A PageElement. - :rtype: bs4.element.Tag | bs4.element.NavigableString - """ - return self._find_all(name, attrs, None, limit, self.parents, - **kwargs) - findParents = find_parents # BS3 - fetchParents = find_parents # BS2 - - @property - def next(self): - """The PageElement, if any, that was parsed just after this one. - - :return: A PageElement. - :rtype: bs4.element.Tag | bs4.element.NavigableString - """ - return self.next_element - - @property - def previous(self): - """The PageElement, if any, that was parsed just before this one. - - :return: A PageElement. - :rtype: bs4.element.Tag | bs4.element.NavigableString - """ - return self.previous_element - - #These methods do the real heavy lifting. - - def _find_one(self, method, name, attrs, text, **kwargs): - r = None - l = method(name, attrs, text, 1, **kwargs) - if l: - r = l[0] - return r - - def _find_all(self, name, attrs, text, limit, generator, **kwargs): - "Iterates over a generator looking for things that match." - - if text is None and 'string' in kwargs: - text = kwargs['string'] - del kwargs['string'] - - if isinstance(name, SoupStrainer): - strainer = name - else: - strainer = SoupStrainer(name, attrs, text, **kwargs) - - if text is None and not limit and not attrs and not kwargs: - if name is True or name is None: - # Optimization to find all tags. - result = (element for element in generator - if isinstance(element, Tag)) - return ResultSet(strainer, result) - elif isinstance(name, str): - # Optimization to find all tags with a given name. - if name.count(':') == 1: - # This is a name with a prefix. If this is a namespace-aware document, - # we need to match the local name against tag.name. If not, - # we need to match the fully-qualified name against tag.name. - prefix, local_name = name.split(':', 1) - else: - prefix = None - local_name = name - result = (element for element in generator - if isinstance(element, Tag) - and ( - element.name == name - ) or ( - element.name == local_name - and (prefix is None or element.prefix == prefix) - ) - ) - return ResultSet(strainer, result) - results = ResultSet(strainer) - while True: - try: - i = next(generator) - except StopIteration: - break - if i: - found = strainer.search(i) - if found: - results.append(found) - if limit and len(results) >= limit: - break - return results - - #These generators can be used to navigate starting from both - #NavigableStrings and Tags. - @property - def next_elements(self): - """All PageElements that were parsed after this one. - - :yield: A sequence of PageElements. - """ - i = self.next_element - while i is not None: - yield i - i = i.next_element - - @property - def next_siblings(self): - """All PageElements that are siblings of this one but were parsed - later. - - :yield: A sequence of PageElements. - """ - i = self.next_sibling - while i is not None: - yield i - i = i.next_sibling - - @property - def previous_elements(self): - """All PageElements that were parsed before this one. - - :yield: A sequence of PageElements. - """ - i = self.previous_element - while i is not None: - yield i - i = i.previous_element - - @property - def previous_siblings(self): - """All PageElements that are siblings of this one but were parsed - earlier. - - :yield: A sequence of PageElements. - """ - i = self.previous_sibling - while i is not None: - yield i - i = i.previous_sibling - - @property - def parents(self): - """All PageElements that are parents of this PageElement. - - :yield: A sequence of PageElements. - """ - i = self.parent - while i is not None: - yield i - i = i.parent - - @property - def decomposed(self): - """Check whether a PageElement has been decomposed. - - :rtype: bool - """ - return getattr(self, '_decomposed', False) or False - - # Old non-property versions of the generators, for backwards - # compatibility with BS3. - def nextGenerator(self): - return self.next_elements - - def nextSiblingGenerator(self): - return self.next_siblings - - def previousGenerator(self): - return self.previous_elements - - def previousSiblingGenerator(self): - return self.previous_siblings - - def parentGenerator(self): - return self.parents - - -class NavigableString(str, PageElement): - """A Python Unicode string that is part of a parse tree. - - When Beautiful Soup parses the markup penguin, it will - create a NavigableString for the string "penguin". - """ - - PREFIX = '' - SUFFIX = '' - - # We can't tell just by looking at a string whether it's contained - # in an XML document or an HTML document. - - known_xml = None - - def __new__(cls, value): - """Create a new NavigableString. - - When unpickling a NavigableString, this method is called with - the string in DEFAULT_OUTPUT_ENCODING. That encoding needs to be - passed in to the superclass's __new__ or the superclass won't know - how to handle non-ASCII characters. - """ - if isinstance(value, str): - u = str.__new__(cls, value) - else: - u = str.__new__(cls, value, DEFAULT_OUTPUT_ENCODING) - u.setup() - return u - - def __copy__(self): - """A copy of a NavigableString has the same contents and class - as the original, but it is not connected to the parse tree. - """ - return type(self)(self) - - def __getnewargs__(self): - return (str(self),) - - def __getattr__(self, attr): - """text.string gives you text. This is for backwards - compatibility for Navigable*String, but for CData* it lets you - get the string without the CData wrapper.""" - if attr == 'string': - return self - else: - raise AttributeError( - "'%s' object has no attribute '%s'" % ( - self.__class__.__name__, attr)) - - def output_ready(self, formatter="minimal"): - """Run the string through the provided formatter. - - :param formatter: A Formatter object, or a string naming one of the standard formatters. - """ - output = self.format_string(self, formatter) - return self.PREFIX + output + self.SUFFIX - - @property - def name(self): - """Since a NavigableString is not a Tag, it has no .name. - - This property is implemented so that code like this doesn't crash - when run on a mixture of Tag and NavigableString objects: - [x.name for x in tag.children] - """ - return None - - @name.setter - def name(self, name): - """Prevent NavigableString.name from ever being set.""" - raise AttributeError("A NavigableString cannot be given a name.") - - -class PreformattedString(NavigableString): - """A NavigableString not subject to the normal formatting rules. - - This is an abstract class used for special kinds of strings such - as comments (the Comment class) and CDATA blocks (the CData - class). - """ - - PREFIX = '' - SUFFIX = '' - - def output_ready(self, formatter=None): - """Make this string ready for output by adding any subclass-specific - prefix or suffix. - - :param formatter: A Formatter object, or a string naming one - of the standard formatters. The string will be passed into the - Formatter, but only to trigger any side effects: the return - value is ignored. - - :return: The string, with any subclass-specific prefix and - suffix added on. - """ - if formatter is not None: - ignore = self.format_string(self, formatter) - return self.PREFIX + self + self.SUFFIX - -class CData(PreformattedString): - """A CDATA block.""" - PREFIX = '' - -class ProcessingInstruction(PreformattedString): - """A SGML processing instruction.""" - - PREFIX = '' - -class XMLProcessingInstruction(ProcessingInstruction): - """An XML processing instruction.""" - PREFIX = '' - -class Comment(PreformattedString): - """An HTML or XML comment.""" - PREFIX = '' - - -class Declaration(PreformattedString): - """An XML declaration.""" - PREFIX = '' - - -class Doctype(PreformattedString): - """A document type declaration.""" - @classmethod - def for_name_and_ids(cls, name, pub_id, system_id): - """Generate an appropriate document type declaration for a given - public ID and system ID. - - :param name: The name of the document's root element, e.g. 'html'. - :param pub_id: The Formal Public Identifier for this document type, - e.g. '-//W3C//DTD XHTML 1.1//EN' - :param system_id: The system identifier for this document type, - e.g. 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd' - - :return: A Doctype. - """ - value = name or '' - if pub_id is not None: - value += ' PUBLIC "%s"' % pub_id - if system_id is not None: - value += ' "%s"' % system_id - elif system_id is not None: - value += ' SYSTEM "%s"' % system_id - - return Doctype(value) - - PREFIX = '\n' - - -class Stylesheet(NavigableString): - """A NavigableString representing an stylesheet (probably - CSS). - - Used to distinguish embedded stylesheets from textual content. - """ - pass - - -class Script(NavigableString): - """A NavigableString representing an executable script (probably - Javascript). - - Used to distinguish executable code from textual content. - """ - pass - - -class TemplateString(NavigableString): - """A NavigableString representing a string found inside an HTML - template embedded in a larger document. - - Used to distinguish such strings from the main body of the document. - """ - pass - - -class Tag(PageElement): - """Represents an HTML or XML tag that is part of a parse tree, along - with its attributes and contents. - - When Beautiful Soup parses the markup penguin, it will - create a Tag object representing the tag. - """ - - def __init__(self, parser=None, builder=None, name=None, namespace=None, - prefix=None, attrs=None, parent=None, previous=None, - is_xml=None, sourceline=None, sourcepos=None, - can_be_empty_element=None, cdata_list_attributes=None, - preserve_whitespace_tags=None - ): - """Basic constructor. - - :param parser: A BeautifulSoup object. - :param builder: A TreeBuilder. - :param name: The name of the tag. - :param namespace: The URI of this Tag's XML namespace, if any. - :param prefix: The prefix for this Tag's XML namespace, if any. - :param attrs: A dictionary of this Tag's attribute values. - :param parent: The PageElement to use as this Tag's parent. - :param previous: The PageElement that was parsed immediately before - this tag. - :param is_xml: If True, this is an XML tag. Otherwise, this is an - HTML tag. - :param sourceline: The line number where this tag was found in its - source document. - :param sourcepos: The character position within `sourceline` where this - tag was found. - :param can_be_empty_element: If True, this tag should be - represented as . If False, this tag should be represented - as . - :param cdata_list_attributes: A list of attributes whose values should - be treated as CDATA if they ever show up on this tag. - :param preserve_whitespace_tags: A list of tag names whose contents - should have their whitespace preserved. - """ - if parser is None: - self.parser_class = None - else: - # We don't actually store the parser object: that lets extracted - # chunks be garbage-collected. - self.parser_class = parser.__class__ - if name is None: - raise ValueError("No value provided for new tag's name.") - self.name = name - self.namespace = namespace - self.prefix = prefix - if ((not builder or builder.store_line_numbers) - and (sourceline is not None or sourcepos is not None)): - self.sourceline = sourceline - self.sourcepos = sourcepos - if attrs is None: - attrs = {} - elif attrs: - if builder is not None and builder.cdata_list_attributes: - attrs = builder._replace_cdata_list_attribute_values( - self.name, attrs) - else: - attrs = dict(attrs) - else: - attrs = dict(attrs) - - # If possible, determine ahead of time whether this tag is an - # XML tag. - if builder: - self.known_xml = builder.is_xml - else: - self.known_xml = is_xml - self.attrs = attrs - self.contents = [] - self.setup(parent, previous) - self.hidden = False - - if builder is None: - # In the absence of a TreeBuilder, use whatever values were - # passed in here. They're probably None, unless this is a copy of some - # other tag. - self.can_be_empty_element = can_be_empty_element - self.cdata_list_attributes = cdata_list_attributes - self.preserve_whitespace_tags = preserve_whitespace_tags - else: - # Set up any substitutions for this tag, such as the charset in a META tag. - builder.set_up_substitutions(self) - - # Ask the TreeBuilder whether this tag might be an empty-element tag. - self.can_be_empty_element = builder.can_be_empty_element(name) - - # Keep track of the list of attributes of this tag that - # might need to be treated as a list. - # - # For performance reasons, we store the whole data structure - # rather than asking the question of every tag. Asking would - # require building a new data structure every time, and - # (unlike can_be_empty_element), we almost never need - # to check this. - self.cdata_list_attributes = builder.cdata_list_attributes - - # Keep track of the names that might cause this tag to be treated as a - # whitespace-preserved tag. - self.preserve_whitespace_tags = builder.preserve_whitespace_tags - - parserClass = _alias("parser_class") # BS3 - - def __copy__(self): - """A copy of a Tag is a new Tag, unconnected to the parse tree. - Its contents are a copy of the old Tag's contents. - """ - clone = type(self)( - None, self.builder, self.name, self.namespace, - self.prefix, self.attrs, is_xml=self._is_xml, - sourceline=self.sourceline, sourcepos=self.sourcepos, - can_be_empty_element=self.can_be_empty_element, - cdata_list_attributes=self.cdata_list_attributes, - preserve_whitespace_tags=self.preserve_whitespace_tags - ) - for attr in ('can_be_empty_element', 'hidden'): - setattr(clone, attr, getattr(self, attr)) - for child in self.contents: - clone.append(child.__copy__()) - return clone - - @property - def is_empty_element(self): - """Is this tag an empty-element tag? (aka a self-closing tag) - - A tag that has contents is never an empty-element tag. - - A tag that has no contents may or may not be an empty-element - tag. It depends on the builder used to create the tag. If the - builder has a designated list of empty-element tags, then only - a tag whose name shows up in that list is considered an - empty-element tag. - - If the builder has no designated list of empty-element tags, - then any tag with no contents is an empty-element tag. - """ - return len(self.contents) == 0 and self.can_be_empty_element - isSelfClosing = is_empty_element # BS3 - - @property - def string(self): - """Convenience property to get the single string within this - PageElement. - - TODO It might make sense to have NavigableString.string return - itself. - - :return: If this element has a single string child, return - value is that string. If this element has one child tag, - return value is the 'string' attribute of the child tag, - recursively. If this element is itself a string, has no - children, or has more than one child, return value is None. - """ - if len(self.contents) != 1: - return None - child = self.contents[0] - if isinstance(child, NavigableString): - return child - return child.string - - @string.setter - def string(self, string): - """Replace this PageElement's contents with `string`.""" - self.clear() - self.append(string.__class__(string)) - - def _all_strings(self, strip=False, types=(NavigableString, CData)): - """Yield all strings of certain classes, possibly stripping them. - - :param strip: If True, all strings will be stripped before being - yielded. - - :types: A tuple of NavigableString subclasses. Any strings of - a subclass not found in this list will be ignored. By - default, this means only NavigableString and CData objects - will be considered. So no comments, processing instructions, - etc. - - :yield: A sequence of strings. - """ - for descendant in self.descendants: - if ( - (types is None and not isinstance(descendant, NavigableString)) - or - (types is not None and type(descendant) not in types)): - continue - if strip: - descendant = descendant.strip() - if len(descendant) == 0: - continue - yield descendant - - strings = property(_all_strings) - - @property - def stripped_strings(self): - """Yield all strings in the document, stripping them first. - - :yield: A sequence of stripped strings. - """ - for string in self._all_strings(True): - yield string - - def get_text(self, separator="", strip=False, - types=(NavigableString, CData)): - """Get all child strings, concatenated using the given separator. - - :param separator: Strings will be concatenated using this separator. - - :param strip: If True, strings will be stripped before being - concatenated. - - :types: A tuple of NavigableString subclasses. Any strings of - a subclass not found in this list will be ignored. By - default, this means only NavigableString and CData objects - will be considered. So no comments, processing instructions, - stylesheets, etc. - - :return: A string. - """ - return separator.join([s for s in self._all_strings( - strip, types=types)]) - getText = get_text - text = property(get_text) - - def decompose(self): - """Recursively destroys this PageElement and its children. - - This element will be removed from the tree and wiped out; so - will everything beneath it. - - The behavior of a decomposed PageElement is undefined and you - should never use one for anything, but if you need to _check_ - whether an element has been decomposed, you can use the - `decomposed` property. - """ - self.extract() - i = self - while i is not None: - n = i.next_element - i.__dict__.clear() - i.contents = [] - i._decomposed = True - i = n - - def clear(self, decompose=False): - """Wipe out all children of this PageElement by calling extract() - on them. - - :param decompose: If this is True, decompose() (a more - destructive method) will be called instead of extract(). - """ - if decompose: - for element in self.contents[:]: - if isinstance(element, Tag): - element.decompose() - else: - element.extract() - else: - for element in self.contents[:]: - element.extract() - - def smooth(self): - """Smooth out this element's children by consolidating consecutive - strings. - - This makes pretty-printed output look more natural following a - lot of operations that modified the tree. - """ - # Mark the first position of every pair of children that need - # to be consolidated. Do this rather than making a copy of - # self.contents, since in most cases very few strings will be - # affected. - marked = [] - for i, a in enumerate(self.contents): - if isinstance(a, Tag): - # Recursively smooth children. - a.smooth() - if i == len(self.contents)-1: - # This is the last item in .contents, and it's not a - # tag. There's no chance it needs any work. - continue - b = self.contents[i+1] - if (isinstance(a, NavigableString) - and isinstance(b, NavigableString) - and not isinstance(a, PreformattedString) - and not isinstance(b, PreformattedString) - ): - marked.append(i) - - # Go over the marked positions in reverse order, so that - # removing items from .contents won't affect the remaining - # positions. - for i in reversed(marked): - a = self.contents[i] - b = self.contents[i+1] - b.extract() - n = NavigableString(a+b) - a.replace_with(n) - - def index(self, element): - """Find the index of a child by identity, not value. - - Avoids issues with tag.contents.index(element) getting the - index of equal elements. - - :param element: Look for this PageElement in `self.contents`. - """ - for i, child in enumerate(self.contents): - if child is element: - return i - raise ValueError("Tag.index: element not in tag") - - def get(self, key, default=None): - """Returns the value of the 'key' attribute for the tag, or - the value given for 'default' if it doesn't have that - attribute.""" - return self.attrs.get(key, default) - - def get_attribute_list(self, key, default=None): - """The same as get(), but always returns a list. - - :param key: The attribute to look for. - :param default: Use this value if the attribute is not present - on this PageElement. - :return: A list of values, probably containing only a single - value. - """ - value = self.get(key, default) - if not isinstance(value, list): - value = [value] - return value - - def has_attr(self, key): - """Does this PageElement have an attribute with the given name?""" - return key in self.attrs - - def __hash__(self): - return str(self).__hash__() - - def __getitem__(self, key): - """tag[key] returns the value of the 'key' attribute for the Tag, - and throws an exception if it's not there.""" - return self.attrs[key] - - def __iter__(self): - "Iterating over a Tag iterates over its contents." - return iter(self.contents) - - def __len__(self): - "The length of a Tag is the length of its list of contents." - return len(self.contents) - - def __contains__(self, x): - return x in self.contents - - def __bool__(self): - "A tag is non-None even if it has no contents." - return True - - def __setitem__(self, key, value): - """Setting tag[key] sets the value of the 'key' attribute for the - tag.""" - self.attrs[key] = value - - def __delitem__(self, key): - "Deleting tag[key] deletes all 'key' attributes for the tag." - self.attrs.pop(key, None) - - def __call__(self, *args, **kwargs): - """Calling a Tag like a function is the same as calling its - find_all() method. Eg. tag('a') returns a list of all the A tags - found within this tag.""" - return self.find_all(*args, **kwargs) - - def __getattr__(self, tag): - """Calling tag.subtag is the same as calling tag.find(name="subtag")""" - #print("Getattr %s.%s" % (self.__class__, tag)) - if len(tag) > 3 and tag.endswith('Tag'): - # BS3: soup.aTag -> "soup.find("a") - tag_name = tag[:-3] - warnings.warn( - '.%(name)sTag is deprecated, use .find("%(name)s") instead. If you really were looking for a tag called %(name)sTag, use .find("%(name)sTag")' % dict( - name=tag_name - ) - ) - return self.find(tag_name) - # We special case contents to avoid recursion. - elif not tag.startswith("__") and not tag == "contents": - return self.find(tag) - raise AttributeError( - "'%s' object has no attribute '%s'" % (self.__class__, tag)) - - def __eq__(self, other): - """Returns true iff this Tag has the same name, the same attributes, - and the same contents (recursively) as `other`.""" - if self is other: - return True - if (not hasattr(other, 'name') or - not hasattr(other, 'attrs') or - not hasattr(other, 'contents') or - self.name != other.name or - self.attrs != other.attrs or - len(self) != len(other)): - return False - for i, my_child in enumerate(self.contents): - if my_child != other.contents[i]: - return False - return True - - def __ne__(self, other): - """Returns true iff this Tag is not identical to `other`, - as defined in __eq__.""" - return not self == other - - def __repr__(self, encoding="unicode-escape"): - """Renders this PageElement as a string. - - :param encoding: The encoding to use (Python 2 only). - :return: Under Python 2, a bytestring; under Python 3, - a Unicode string. - """ - if PY3K: - # "The return value must be a string object", i.e. Unicode - return self.decode() - else: - # "The return value must be a string object", i.e. a bytestring. - # By convention, the return value of __repr__ should also be - # an ASCII string. - return self.encode(encoding) - - def __unicode__(self): - """Renders this PageElement as a Unicode string.""" - return self.decode() - - def __str__(self): - """Renders this PageElement as a generic string. - - :return: Under Python 2, a UTF-8 bytestring; under Python 3, - a Unicode string. - """ - if PY3K: - return self.decode() - else: - return self.encode() - - if PY3K: - __str__ = __repr__ = __unicode__ - - def encode(self, encoding=DEFAULT_OUTPUT_ENCODING, - indent_level=None, formatter="minimal", - errors="xmlcharrefreplace"): - """Render a bytestring representation of this PageElement and its - contents. - - :param encoding: The destination encoding. - :param indent_level: Each line of the rendering will be - indented this many spaces. Used internally in - recursive calls while pretty-printing. - :param formatter: A Formatter object, or a string naming one of - the standard formatters. - :param errors: An error handling strategy such as - 'xmlcharrefreplace'. This value is passed along into - encode() and its value should be one of the constants - defined by Python. - :return: A bytestring. - - """ - # Turn the data structure into Unicode, then encode the - # Unicode. - u = self.decode(indent_level, encoding, formatter) - return u.encode(encoding, errors) - - def decode(self, indent_level=None, - eventual_encoding=DEFAULT_OUTPUT_ENCODING, - formatter="minimal"): - """Render a Unicode representation of this PageElement and its - contents. - - :param indent_level: Each line of the rendering will be - indented this many spaces. Used internally in - recursive calls while pretty-printing. - :param eventual_encoding: The tag is destined to be - encoded into this encoding. This method is _not_ - responsible for performing that encoding. This information - is passed in so that it can be substituted in if the - document contains a tag that mentions the document's - encoding. - :param formatter: A Formatter object, or a string naming one of - the standard formatters. - """ - - # First off, turn a non-Formatter `formatter` into a Formatter - # object. This will stop the lookup from happening over and - # over again. - if not isinstance(formatter, Formatter): - formatter = self.formatter_for_name(formatter) - attributes = formatter.attributes(self) - attrs = [] - for key, val in attributes: - if val is None: - decoded = key - else: - if isinstance(val, list) or isinstance(val, tuple): - val = ' '.join(val) - elif not isinstance(val, str): - val = str(val) - elif ( - isinstance(val, AttributeValueWithCharsetSubstitution) - and eventual_encoding is not None - ): - val = val.encode(eventual_encoding) - - text = formatter.attribute_value(val) - decoded = ( - str(key) + '=' - + formatter.quoted_attribute_value(text)) - attrs.append(decoded) - close = '' - closeTag = '' - - prefix = '' - if self.prefix: - prefix = self.prefix + ":" - - if self.is_empty_element: - close = formatter.void_element_close_prefix or '' - else: - closeTag = '' % (prefix, self.name) - - pretty_print = self._should_pretty_print(indent_level) - space = '' - indent_space = '' - if indent_level is not None: - indent_space = (' ' * (indent_level - 1)) - if pretty_print: - space = indent_space - indent_contents = indent_level + 1 - else: - indent_contents = None - contents = self.decode_contents( - indent_contents, eventual_encoding, formatter - ) - - if self.hidden: - # This is the 'document root' object. - s = contents - else: - s = [] - attribute_string = '' - if attrs: - attribute_string = ' ' + ' '.join(attrs) - if indent_level is not None: - # Even if this particular tag is not pretty-printed, - # we should indent up to the start of the tag. - s.append(indent_space) - s.append('<%s%s%s%s>' % ( - prefix, self.name, attribute_string, close)) - if pretty_print: - s.append("\n") - s.append(contents) - if pretty_print and contents and contents[-1] != "\n": - s.append("\n") - if pretty_print and closeTag: - s.append(space) - s.append(closeTag) - if indent_level is not None and closeTag and self.next_sibling: - # Even if this particular tag is not pretty-printed, - # we're now done with the tag, and we should add a - # newline if appropriate. - s.append("\n") - s = ''.join(s) - return s - - def _should_pretty_print(self, indent_level): - """Should this tag be pretty-printed? - - Most of them should, but some (such as
 in HTML
-        documents) should not.
-        """
-        return (
-            indent_level is not None
-            and (
-                not self.preserve_whitespace_tags
-                or self.name not in self.preserve_whitespace_tags
-            )
-        )
-
-    def prettify(self, encoding=None, formatter="minimal"):
-        """Pretty-print this PageElement as a string.
-
-        :param encoding: The eventual encoding of the string. If this is None,
-            a Unicode string will be returned.
-        :param formatter: A Formatter object, or a string naming one of
-            the standard formatters.
-        :return: A Unicode string (if encoding==None) or a bytestring 
-            (otherwise).
-        """
-        if encoding is None:
-            return self.decode(True, formatter=formatter)
-        else:
-            return self.encode(encoding, True, formatter=formatter)
-
-    def decode_contents(self, indent_level=None,
-                       eventual_encoding=DEFAULT_OUTPUT_ENCODING,
-                       formatter="minimal"):
-        """Renders the contents of this tag as a Unicode string.
-
-        :param indent_level: Each line of the rendering will be
-           indented this many spaces. Used internally in
-           recursive calls while pretty-printing.
-
-        :param eventual_encoding: The tag is destined to be
-           encoded into this encoding. decode_contents() is _not_
-           responsible for performing that encoding. This information
-           is passed in so that it can be substituted in if the
-           document contains a  tag that mentions the document's
-           encoding.
-
-        :param formatter: A Formatter object, or a string naming one of
-            the standard Formatters.
-        """
-        # First off, turn a string formatter into a Formatter object. This
-        # will stop the lookup from happening over and over again.
-        if not isinstance(formatter, Formatter):
-            formatter = self.formatter_for_name(formatter)
-
-        pretty_print = (indent_level is not None)
-        s = []
-        for c in self:
-            text = None
-            if isinstance(c, NavigableString):
-                text = c.output_ready(formatter)
-            elif isinstance(c, Tag):
-                s.append(c.decode(indent_level, eventual_encoding,
-                                  formatter))
-            preserve_whitespace = (
-                self.preserve_whitespace_tags and self.name in self.preserve_whitespace_tags
-            )
-            if text and indent_level and not preserve_whitespace:
-                text = text.strip()
-            if text:
-                if pretty_print and not preserve_whitespace:
-                    s.append(" " * (indent_level - 1))
-                s.append(text)
-                if pretty_print and not preserve_whitespace:
-                    s.append("\n")
-        return ''.join(s)
-       
-    def encode_contents(
-        self, indent_level=None, encoding=DEFAULT_OUTPUT_ENCODING,
-        formatter="minimal"):
-        """Renders the contents of this PageElement as a bytestring.
-
-        :param indent_level: Each line of the rendering will be
-           indented this many spaces. Used internally in
-           recursive calls while pretty-printing.
-
-        :param eventual_encoding: The bytestring will be in this encoding.
-
-        :param formatter: A Formatter object, or a string naming one of
-            the standard Formatters.
-
-        :return: A bytestring.
-        """
-        contents = self.decode_contents(indent_level, encoding, formatter)
-        return contents.encode(encoding)
-
-    # Old method for BS3 compatibility
-    def renderContents(self, encoding=DEFAULT_OUTPUT_ENCODING,
-                       prettyPrint=False, indentLevel=0):
-        """Deprecated method for BS3 compatibility."""
-        if not prettyPrint:
-            indentLevel = None
-        return self.encode_contents(
-            indent_level=indentLevel, encoding=encoding)
-
-    #Soup methods
-
-    def find(self, name=None, attrs={}, recursive=True, text=None,
-             **kwargs):
-        """Look in the children of this PageElement and find the first
-        PageElement that matches the given criteria.
-
-        All find_* methods take a common set of arguments. See the online
-        documentation for detailed explanations.
-
-        :param name: A filter on tag name.
-        :param attrs: A dictionary of filters on attribute values.
-        :param recursive: If this is True, find() will perform a
-            recursive search of this PageElement's children. Otherwise,
-            only the direct children will be considered.
-        :param limit: Stop looking after finding this many results.
-        :kwargs: A dictionary of filters on attribute values.
-        :return: A PageElement.
-        :rtype: bs4.element.Tag | bs4.element.NavigableString
-        """
-        r = None
-        l = self.find_all(name, attrs, recursive, text, 1, **kwargs)
-        if l:
-            r = l[0]
-        return r
-    findChild = find #BS2
-
-    def find_all(self, name=None, attrs={}, recursive=True, text=None,
-                 limit=None, **kwargs):
-        """Look in the children of this PageElement and find all
-        PageElements that match the given criteria.
-
-        All find_* methods take a common set of arguments. See the online
-        documentation for detailed explanations.
-
-        :param name: A filter on tag name.
-        :param attrs: A dictionary of filters on attribute values.
-        :param recursive: If this is True, find_all() will perform a
-            recursive search of this PageElement's children. Otherwise,
-            only the direct children will be considered.
-        :param limit: Stop looking after finding this many results.
-        :kwargs: A dictionary of filters on attribute values.
-        :return: A ResultSet of PageElements.
-        :rtype: bs4.element.ResultSet
-        """
-        generator = self.descendants
-        if not recursive:
-            generator = self.children
-        return self._find_all(name, attrs, text, limit, generator, **kwargs)
-    findAll = find_all       # BS3
-    findChildren = find_all  # BS2
-
-    #Generator methods
-    @property
-    def children(self):
-        """Iterate over all direct children of this PageElement.
-
-        :yield: A sequence of PageElements.
-        """
-        # return iter() to make the purpose of the method clear
-        return iter(self.contents)  # XXX This seems to be untested.
-
-    @property
-    def descendants(self):
-        """Iterate over all children of this PageElement in a
-        breadth-first sequence.
-
-        :yield: A sequence of PageElements.
-        """
-        if not len(self.contents):
-            return
-        stopNode = self._last_descendant().next_element
-        current = self.contents[0]
-        while current is not stopNode:
-            yield current
-            current = current.next_element
-
-    # CSS selector code
-    def select_one(self, selector, namespaces=None, **kwargs):
-        """Perform a CSS selection operation on the current element.
-
-        :param selector: A CSS selector.
-
-        :param namespaces: A dictionary mapping namespace prefixes
-           used in the CSS selector to namespace URIs. By default,
-           Beautiful Soup will use the prefixes it encountered while
-           parsing the document.
-
-        :param kwargs: Keyword arguments to be passed into SoupSieve's 
-           soupsieve.select() method.
-
-        :return: A Tag.
-        :rtype: bs4.element.Tag
-        """
-        value = self.select(selector, namespaces, 1, **kwargs)
-        if value:
-            return value[0]
-        return None
-
-    def select(self, selector, namespaces=None, limit=None, **kwargs):
-        """Perform a CSS selection operation on the current element.
-
-        This uses the SoupSieve library.
-
-        :param selector: A string containing a CSS selector.
-
-        :param namespaces: A dictionary mapping namespace prefixes
-           used in the CSS selector to namespace URIs. By default,
-           Beautiful Soup will use the prefixes it encountered while
-           parsing the document.
-
-        :param limit: After finding this number of results, stop looking.
-
-        :param kwargs: Keyword arguments to be passed into SoupSieve's 
-           soupsieve.select() method.
-
-        :return: A ResultSet of Tags.
-        :rtype: bs4.element.ResultSet
-        """
-        if namespaces is None:
-            namespaces = self._namespaces
-        
-        if limit is None:
-            limit = 0
-        if soupsieve is None:
-            raise NotImplementedError(
-                "Cannot execute CSS selectors because the soupsieve package is not installed."
-            )
-            
-        results = soupsieve.select(selector, self, namespaces, limit, **kwargs)
-
-        # We do this because it's more consistent and because
-        # ResultSet.__getattr__ has a helpful error message.
-        return ResultSet(None, results)
-
-    # Old names for backwards compatibility
-    def childGenerator(self):
-        """Deprecated generator."""
-        return self.children
-
-    def recursiveChildGenerator(self):
-        """Deprecated generator."""
-        return self.descendants
-
-    def has_key(self, key):
-        """Deprecated method. This was kind of misleading because has_key()
-        (attributes) was different from __in__ (contents).
-
-        has_key() is gone in Python 3, anyway.
-        """
-        warnings.warn('has_key is deprecated. Use has_attr("%s") instead.' % (
-                key))
-        return self.has_attr(key)
-
-# Next, a couple classes to represent queries and their results.
-class SoupStrainer(object):
-    """Encapsulates a number of ways of matching a markup element (tag or
-    string).
-
-    This is primarily used to underpin the find_* methods, but you can
-    create one yourself and pass it in as `parse_only` to the
-    `BeautifulSoup` constructor, to parse a subset of a large
-    document.
-    """
-
-    def __init__(self, name=None, attrs={}, text=None, **kwargs):
-        """Constructor.
-
-        The SoupStrainer constructor takes the same arguments passed
-        into the find_* methods. See the online documentation for
-        detailed explanations.
-
-        :param name: A filter on tag name.
-        :param attrs: A dictionary of filters on attribute values.
-        :param text: A filter for a NavigableString with specific text.
-        :kwargs: A dictionary of filters on attribute values.
-        """        
-        self.name = self._normalize_search_value(name)
-        if not isinstance(attrs, dict):
-            # Treat a non-dict value for attrs as a search for the 'class'
-            # attribute.
-            kwargs['class'] = attrs
-            attrs = None
-
-        if 'class_' in kwargs:
-            # Treat class_="foo" as a search for the 'class'
-            # attribute, overriding any non-dict value for attrs.
-            kwargs['class'] = kwargs['class_']
-            del kwargs['class_']
-
-        if kwargs:
-            if attrs:
-                attrs = attrs.copy()
-                attrs.update(kwargs)
-            else:
-                attrs = kwargs
-        normalized_attrs = {}
-        for key, value in list(attrs.items()):
-            normalized_attrs[key] = self._normalize_search_value(value)
-
-        self.attrs = normalized_attrs
-        self.text = self._normalize_search_value(text)
-
-    def _normalize_search_value(self, value):
-        # Leave it alone if it's a Unicode string, a callable, a
-        # regular expression, a boolean, or None.
-        if (isinstance(value, str) or isinstance(value, Callable) or hasattr(value, 'match')
-            or isinstance(value, bool) or value is None):
-            return value
-
-        # If it's a bytestring, convert it to Unicode, treating it as UTF-8.
-        if isinstance(value, bytes):
-            return value.decode("utf8")
-
-        # If it's listlike, convert it into a list of strings.
-        if hasattr(value, '__iter__'):
-            new_value = []
-            for v in value:
-                if (hasattr(v, '__iter__') and not isinstance(v, bytes)
-                    and not isinstance(v, str)):
-                    # This is almost certainly the user's mistake. In the
-                    # interests of avoiding infinite loops, we'll let
-                    # it through as-is rather than doing a recursive call.
-                    new_value.append(v)
-                else:
-                    new_value.append(self._normalize_search_value(v))
-            return new_value
-
-        # Otherwise, convert it into a Unicode string.
-        # The unicode(str()) thing is so this will do the same thing on Python 2
-        # and Python 3.
-        return str(str(value))
-
-    def __str__(self):
-        """A human-readable representation of this SoupStrainer."""
-        if self.text:
-            return self.text
-        else:
-            return "%s|%s" % (self.name, self.attrs)
-
-    def search_tag(self, markup_name=None, markup_attrs={}):
-        """Check whether a Tag with the given name and attributes would
-        match this SoupStrainer.
-
-        Used prospectively to decide whether to even bother creating a Tag
-        object.
-
-        :param markup_name: A tag name as found in some markup.
-        :param markup_attrs: A dictionary of attributes as found in some markup.
-
-        :return: True if the prospective tag would match this SoupStrainer;
-            False otherwise.
-        """
-        found = None
-        markup = None
-        if isinstance(markup_name, Tag):
-            markup = markup_name
-            markup_attrs = markup
-        call_function_with_tag_data = (
-            isinstance(self.name, Callable)
-            and not isinstance(markup_name, Tag))
-
-        if ((not self.name)
-            or call_function_with_tag_data
-            or (markup and self._matches(markup, self.name))
-            or (not markup and self._matches(markup_name, self.name))):
-            if call_function_with_tag_data:
-                match = self.name(markup_name, markup_attrs)
-            else:
-                match = True
-                markup_attr_map = None
-                for attr, match_against in list(self.attrs.items()):
-                    if not markup_attr_map:
-                        if hasattr(markup_attrs, 'get'):
-                            markup_attr_map = markup_attrs
-                        else:
-                            markup_attr_map = {}
-                            for k, v in markup_attrs:
-                                markup_attr_map[k] = v
-                    attr_value = markup_attr_map.get(attr)
-                    if not self._matches(attr_value, match_against):
-                        match = False
-                        break
-            if match:
-                if markup:
-                    found = markup
-                else:
-                    found = markup_name
-        if found and self.text and not self._matches(found.string, self.text):
-            found = None
-        return found
-
-    # For BS3 compatibility.
-    searchTag = search_tag
-
-    def search(self, markup):
-        """Find all items in `markup` that match this SoupStrainer.
-
-        Used by the core _find_all() method, which is ultimately
-        called by all find_* methods.
-
-        :param markup: A PageElement or a list of them.
-        """
-        # print('looking for %s in %s' % (self, markup))
-        found = None
-        # If given a list of items, scan it for a text element that
-        # matches.
-        if hasattr(markup, '__iter__') and not isinstance(markup, (Tag, str)):
-            for element in markup:
-                if isinstance(element, NavigableString) \
-                       and self.search(element):
-                    found = element
-                    break
-        # If it's a Tag, make sure its name or attributes match.
-        # Don't bother with Tags if we're searching for text.
-        elif isinstance(markup, Tag):
-            if not self.text or self.name or self.attrs:
-                found = self.search_tag(markup)
-        # If it's text, make sure the text matches.
-        elif isinstance(markup, NavigableString) or \
-                 isinstance(markup, str):
-            if not self.name and not self.attrs and self._matches(markup, self.text):
-                found = markup
-        else:
-            raise Exception(
-                "I don't know how to match against a %s" % markup.__class__)
-        return found
-
-    def _matches(self, markup, match_against, already_tried=None):
-        # print(u"Matching %s against %s" % (markup, match_against))
-        result = False
-        if isinstance(markup, list) or isinstance(markup, tuple):
-            # This should only happen when searching a multi-valued attribute
-            # like 'class'.
-            for item in markup:
-                if self._matches(item, match_against):
-                    return True
-            # We didn't match any particular value of the multivalue
-            # attribute, but maybe we match the attribute value when
-            # considered as a string.
-            if self._matches(' '.join(markup), match_against):
-                return True
-            return False
-        
-        if match_against is True:
-            # True matches any non-None value.
-            return markup is not None
-
-        if isinstance(match_against, Callable):
-            return match_against(markup)
-
-        # Custom callables take the tag as an argument, but all
-        # other ways of matching match the tag name as a string.
-        original_markup = markup
-        if isinstance(markup, Tag):
-            markup = markup.name
-
-        # Ensure that `markup` is either a Unicode string, or None.
-        markup = self._normalize_search_value(markup)
-
-        if markup is None:
-            # None matches None, False, an empty string, an empty list, and so on.
-            return not match_against
-
-        if (hasattr(match_against, '__iter__')
-            and not isinstance(match_against, str)):
-            # We're asked to match against an iterable of items.
-            # The markup must be match at least one item in the
-            # iterable. We'll try each one in turn.
-            #
-            # To avoid infinite recursion we need to keep track of
-            # items we've already seen.
-            if not already_tried:
-                already_tried = set()
-            for item in match_against:
-                if item.__hash__:
-                    key = item
-                else:
-                    key = id(item)
-                if key in already_tried:
-                    continue
-                else:
-                    already_tried.add(key)
-                    if self._matches(original_markup, item, already_tried):
-                        return True
-            else:
-                return False
-        
-        # Beyond this point we might need to run the test twice: once against
-        # the tag's name and once against its prefixed name.
-        match = False
-        
-        if not match and isinstance(match_against, str):
-            # Exact string match
-            match = markup == match_against
-
-        if not match and hasattr(match_against, 'search'):
-            # Regexp match
-            return match_against.search(markup)
-
-        if (not match
-            and isinstance(original_markup, Tag)
-            and original_markup.prefix):
-            # Try the whole thing again with the prefixed tag name.
-            return self._matches(
-                original_markup.prefix + ':' + original_markup.name, match_against
-            )
-
-        return match
-
-
-class ResultSet(list):
-    """A ResultSet is just a list that keeps track of the SoupStrainer
-    that created it."""
-    def __init__(self, source, result=()):
-        """Constructor.
-
-        :param source: A SoupStrainer.
-        :param result: A list of PageElements.
-        """
-        super(ResultSet, self).__init__(result)
-        self.source = source
-
-    def __getattr__(self, key):
-        """Raise a helpful exception to explain a common code fix."""
-        raise AttributeError(
-            "ResultSet object has no attribute '%s'. You're probably treating a list of elements like a single element. Did you call find_all() when you meant to call find()?" % key
-        )
diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4/formatter.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4/formatter.py
deleted file mode 100644
index 2cbab4c..0000000
--- a/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4/formatter.py
+++ /dev/null
@@ -1,152 +0,0 @@
-from bs4.dammit import EntitySubstitution
-
-class Formatter(EntitySubstitution):
-    """Describes a strategy to use when outputting a parse tree to a string.
-
-    Some parts of this strategy come from the distinction between
-    HTML4, HTML5, and XML. Others are configurable by the user.
-
-    Formatters are passed in as the `formatter` argument to methods
-    like `PageElement.encode`. Most people won't need to think about
-    formatters, and most people who need to think about them can pass
-    in one of these predefined strings as `formatter` rather than
-    making a new Formatter object:
-
-    For HTML documents:
-     * 'html' - HTML entity substitution for generic HTML documents. (default)
-     * 'html5' - HTML entity substitution for HTML5 documents.
-     * 'minimal' - Only make the substitutions necessary to guarantee
-                   valid HTML.
-     * None - Do not perform any substitution. This will be faster
-              but may result in invalid markup.
-
-    For XML documents:
-     * 'html' - Entity substitution for XHTML documents.
-     * 'minimal' - Only make the substitutions necessary to guarantee
-                   valid XML. (default)
-     * None - Do not perform any substitution. This will be faster
-              but may result in invalid markup.
-    """
-    # Registries of XML and HTML formatters.
-    XML_FORMATTERS = {}
-    HTML_FORMATTERS = {}
-
-    HTML = 'html'
-    XML = 'xml'
-
-    HTML_DEFAULTS = dict(
-        cdata_containing_tags=set(["script", "style"]),
-    )
-
-    def _default(self, language, value, kwarg):
-        if value is not None:
-            return value
-        if language == self.XML:
-            return set()
-        return self.HTML_DEFAULTS[kwarg]
-
-    def __init__(
-            self, language=None, entity_substitution=None,
-            void_element_close_prefix='/', cdata_containing_tags=None,
-    ):
-        """Constructor.
-
-        :param language: This should be Formatter.XML if you are formatting
-           XML markup and Formatter.HTML if you are formatting HTML markup.
-
-        :param entity_substitution: A function to call to replace special
-           characters with XML/HTML entities. For examples, see 
-           bs4.dammit.EntitySubstitution.substitute_html and substitute_xml.
-        :param void_element_close_prefix: By default, void elements
-           are represented as  (XML rules) rather than 
-           (HTML rules). To get , pass in the empty string.
-        :param cdata_containing_tags: The list of tags that are defined
-           as containing CDATA in this dialect. For example, in HTML,
-           
-
This numeric entity is missing the final semicolon:
- -
a
-
This document contains (do you see it?)
-
This document ends with That attribute value was bogus
-The doctype is invalid because it contains extra whitespace -
That boolean attribute had no value
-
Here's a nonexistent entity: &#foo; (do you see it?)
-
This document ends before the entity finishes: > -

Paragraphs shouldn't contain block display elements, but this one does:

you see?

-Multiple values for the same attribute. -
Here's a table
-
-
This tag contains nothing but whitespace:
-

This p tag is cut off by

the end of the blockquote tag
-
Here's a nested table:
foo
This table contains bare markup
- -
This document contains a surprise doctype
- -
Tag name contains Unicode characters
- - -""" - - -class SoupTest(unittest.TestCase): - - @property - def default_builder(self): - return default_builder - - def soup(self, markup, **kwargs): - """Build a Beautiful Soup object from markup.""" - builder = kwargs.pop('builder', self.default_builder) - return BeautifulSoup(markup, builder=builder, **kwargs) - - def document_for(self, markup, **kwargs): - """Turn an HTML fragment into a document. - - The details depend on the builder. - """ - return self.default_builder(**kwargs).test_fragment_to_document(markup) - - def assertSoupEquals(self, to_parse, compare_parsed_to=None): - builder = self.default_builder - obj = BeautifulSoup(to_parse, builder=builder) - if compare_parsed_to is None: - compare_parsed_to = to_parse - - self.assertEqual(obj.decode(), self.document_for(compare_parsed_to)) - - def assertConnectedness(self, element): - """Ensure that next_element and previous_element are properly - set for all descendants of the given element. - """ - earlier = None - for e in element.descendants: - if earlier: - self.assertEqual(e, earlier.next_element) - self.assertEqual(earlier, e.previous_element) - earlier = e - - def linkage_validator(self, el, _recursive_call=False): - """Ensure proper linkage throughout the document.""" - descendant = None - # Document element should have no previous element or previous sibling. - # It also shouldn't have a next sibling. - if el.parent is None: - assert el.previous_element is None,\ - "Bad previous_element\nNODE: {}\nPREV: {}\nEXPECTED: {}".format( - el, el.previous_element, None - ) - assert el.previous_sibling is None,\ - "Bad previous_sibling\nNODE: {}\nPREV: {}\nEXPECTED: {}".format( - el, el.previous_sibling, None - ) - assert el.next_sibling is None,\ - "Bad next_sibling\nNODE: {}\nNEXT: {}\nEXPECTED: {}".format( - el, el.next_sibling, None - ) - - idx = 0 - child = None - last_child = None - last_idx = len(el.contents) - 1 - for child in el.contents: - descendant = None - - # Parent should link next element to their first child - # That child should have no previous sibling - if idx == 0: - if el.parent is not None: - assert el.next_element is child,\ - "Bad next_element\nNODE: {}\nNEXT: {}\nEXPECTED: {}".format( - el, el.next_element, child - ) - assert child.previous_element is el,\ - "Bad previous_element\nNODE: {}\nPREV: {}\nEXPECTED: {}".format( - child, child.previous_element, el - ) - assert child.previous_sibling is None,\ - "Bad previous_sibling\nNODE: {}\nPREV {}\nEXPECTED: {}".format( - child, child.previous_sibling, None - ) - - # If not the first child, previous index should link as sibling to this index - # Previous element should match the last index or the last bubbled up descendant - else: - assert child.previous_sibling is el.contents[idx - 1],\ - "Bad previous_sibling\nNODE: {}\nPREV {}\nEXPECTED {}".format( - child, child.previous_sibling, el.contents[idx - 1] - ) - assert el.contents[idx - 1].next_sibling is child,\ - "Bad next_sibling\nNODE: {}\nNEXT {}\nEXPECTED {}".format( - el.contents[idx - 1], el.contents[idx - 1].next_sibling, child - ) - - if last_child is not None: - assert child.previous_element is last_child,\ - "Bad previous_element\nNODE: {}\nPREV {}\nEXPECTED {}\nCONTENTS {}".format( - child, child.previous_element, last_child, child.parent.contents - ) - assert last_child.next_element is child,\ - "Bad next_element\nNODE: {}\nNEXT {}\nEXPECTED {}".format( - last_child, last_child.next_element, child - ) - - if isinstance(child, Tag) and child.contents: - descendant = self.linkage_validator(child, True) - # A bubbled up descendant should have no next siblings - assert descendant.next_sibling is None,\ - "Bad next_sibling\nNODE: {}\nNEXT {}\nEXPECTED {}".format( - descendant, descendant.next_sibling, None - ) - - # Mark last child as either the bubbled up descendant or the current child - if descendant is not None: - last_child = descendant - else: - last_child = child - - # If last child, there are non next siblings - if idx == last_idx: - assert child.next_sibling is None,\ - "Bad next_sibling\nNODE: {}\nNEXT {}\nEXPECTED {}".format( - child, child.next_sibling, None - ) - idx += 1 - - child = descendant if descendant is not None else child - if child is None: - child = el - - if not _recursive_call and child is not None: - target = el - while True: - if target is None: - assert child.next_element is None, \ - "Bad next_element\nNODE: {}\nNEXT {}\nEXPECTED {}".format( - child, child.next_element, None - ) - break - elif target.next_sibling is not None: - assert child.next_element is target.next_sibling, \ - "Bad next_element\nNODE: {}\nNEXT {}\nEXPECTED {}".format( - child, child.next_element, target.next_sibling - ) - break - target = target.parent - - # We are done, so nothing to return - return None - else: - # Return the child to the recursive caller - return child - - -class HTMLTreeBuilderSmokeTest(object): - - """A basic test of a treebuilder's competence. - - Any HTML treebuilder, present or future, should be able to pass - these tests. With invalid markup, there's room for interpretation, - and different parsers can handle it differently. But with the - markup in these tests, there's not much room for interpretation. - """ - - def test_empty_element_tags(self): - """Verify that all HTML4 and HTML5 empty element (aka void element) tags - are handled correctly. - """ - for name in [ - 'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'keygen', 'link', 'menuitem', 'meta', 'param', 'source', 'track', 'wbr', - 'spacer', 'frame' - ]: - soup = self.soup("") - new_tag = soup.new_tag(name) - self.assertEqual(True, new_tag.is_empty_element) - - def test_special_string_containers(self): - soup = self.soup( - "" - ) - assert isinstance(soup.style.string, Stylesheet) - assert isinstance(soup.script.string, Script) - - soup = self.soup( - "" - ) - assert isinstance(soup.style.string, Stylesheet) - # The contents of the style tag resemble an HTML comment, but - # it's not treated as a comment. - self.assertEqual("", soup.style.string) - assert isinstance(soup.style.string, Stylesheet) - - def test_pickle_and_unpickle_identity(self): - # Pickling a tree, then unpickling it, yields a tree identical - # to the original. - tree = self.soup("foo") - dumped = pickle.dumps(tree, 2) - loaded = pickle.loads(dumped) - self.assertEqual(loaded.__class__, BeautifulSoup) - self.assertEqual(loaded.decode(), tree.decode()) - - def assertDoctypeHandled(self, doctype_fragment): - """Assert that a given doctype string is handled correctly.""" - doctype_str, soup = self._document_with_doctype(doctype_fragment) - - # Make sure a Doctype object was created. - doctype = soup.contents[0] - self.assertEqual(doctype.__class__, Doctype) - self.assertEqual(doctype, doctype_fragment) - self.assertEqual( - soup.encode("utf8")[:len(doctype_str)], - doctype_str - ) - - # Make sure that the doctype was correctly associated with the - # parse tree and that the rest of the document parsed. - self.assertEqual(soup.p.contents[0], 'foo') - - def _document_with_doctype(self, doctype_fragment, doctype_string="DOCTYPE"): - """Generate and parse a document with the given doctype.""" - doctype = '' % (doctype_string, doctype_fragment) - markup = doctype + '\n

foo

' - soup = self.soup(markup) - return doctype.encode("utf8"), soup - - def test_normal_doctypes(self): - """Make sure normal, everyday HTML doctypes are handled correctly.""" - self.assertDoctypeHandled("html") - self.assertDoctypeHandled( - 'html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"') - - def test_empty_doctype(self): - soup = self.soup("") - doctype = soup.contents[0] - self.assertEqual("", doctype.strip()) - - def test_mixed_case_doctype(self): - # A lowercase or mixed-case doctype becomes a Doctype. - for doctype_fragment in ("doctype", "DocType"): - doctype_str, soup = self._document_with_doctype( - "html", doctype_fragment - ) - - # Make sure a Doctype object was created and that the DOCTYPE - # is uppercase. - doctype = soup.contents[0] - self.assertEqual(doctype.__class__, Doctype) - self.assertEqual(doctype, "html") - self.assertEqual( - soup.encode("utf8")[:len(doctype_str)], - b"" - ) - - # Make sure that the doctype was correctly associated with the - # parse tree and that the rest of the document parsed. - self.assertEqual(soup.p.contents[0], 'foo') - - def test_public_doctype_with_url(self): - doctype = 'html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"' - self.assertDoctypeHandled(doctype) - - def test_system_doctype(self): - self.assertDoctypeHandled('foo SYSTEM "http://www.example.com/"') - - def test_namespaced_system_doctype(self): - # We can handle a namespaced doctype with a system ID. - self.assertDoctypeHandled('xsl:stylesheet SYSTEM "htmlent.dtd"') - - def test_namespaced_public_doctype(self): - # Test a namespaced doctype with a public id. - self.assertDoctypeHandled('xsl:stylesheet PUBLIC "htmlent.dtd"') - - def test_real_xhtml_document(self): - """A real XHTML document should come out more or less the same as it went in.""" - markup = b""" - - -Hello. -Goodbye. -""" - soup = self.soup(markup) - self.assertEqual( - soup.encode("utf-8").replace(b"\n", b""), - markup.replace(b"\n", b"")) - - def test_namespaced_html(self): - """When a namespaced XML document is parsed as HTML it should - be treated as HTML with weird tag names. - """ - markup = b"""content""" - soup = self.soup(markup) - self.assertEqual(2, len(soup.find_all("ns1:foo"))) - - def test_processing_instruction(self): - # We test both Unicode and bytestring to verify that - # process_markup correctly sets processing_instruction_class - # even when the markup is already Unicode and there is no - # need to process anything. - markup = """""" - soup = self.soup(markup) - self.assertEqual(markup, soup.decode()) - - markup = b"""""" - soup = self.soup(markup) - self.assertEqual(markup, soup.encode("utf8")) - - def test_deepcopy(self): - """Make sure you can copy the tree builder. - - This is important because the builder is part of a - BeautifulSoup object, and we want to be able to copy that. - """ - copy.deepcopy(self.default_builder) - - def test_p_tag_is_never_empty_element(self): - """A

tag is never designated as an empty-element tag. - - Even if the markup shows it as an empty-element tag, it - shouldn't be presented that way. - """ - soup = self.soup("

") - self.assertFalse(soup.p.is_empty_element) - self.assertEqual(str(soup.p), "

") - - def test_unclosed_tags_get_closed(self): - """A tag that's not closed by the end of the document should be closed. - - This applies to all tags except empty-element tags. - """ - self.assertSoupEquals("

", "

") - self.assertSoupEquals("", "") - - self.assertSoupEquals("
", "
") - - def test_br_is_always_empty_element_tag(self): - """A
tag is designated as an empty-element tag. - - Some parsers treat

as one
tag, some parsers as - two tags, but it should always be an empty-element tag. - """ - soup = self.soup("

") - self.assertTrue(soup.br.is_empty_element) - self.assertEqual(str(soup.br), "
") - - def test_nested_formatting_elements(self): - self.assertSoupEquals("") - - def test_double_head(self): - html = ''' - - -Ordinary HEAD element test - - - -Hello, world! - - -''' - soup = self.soup(html) - self.assertEqual("text/javascript", soup.find('script')['type']) - - def test_comment(self): - # Comments are represented as Comment objects. - markup = "

foobaz

" - self.assertSoupEquals(markup) - - soup = self.soup(markup) - comment = soup.find(text="foobar") - self.assertEqual(comment.__class__, Comment) - - # The comment is properly integrated into the tree. - foo = soup.find(text="foo") - self.assertEqual(comment, foo.next_element) - baz = soup.find(text="baz") - self.assertEqual(comment, baz.previous_element) - - def test_preserved_whitespace_in_pre_and_textarea(self): - """Whitespace must be preserved in
 and "
-        self.assertSoupEquals(pre_markup)
-        self.assertSoupEquals(textarea_markup)
-
-        soup = self.soup(pre_markup)
-        self.assertEqual(soup.pre.prettify(), pre_markup)
-
-        soup = self.soup(textarea_markup)
-        self.assertEqual(soup.textarea.prettify(), textarea_markup)
-
-        soup = self.soup("")
-        self.assertEqual(soup.textarea.prettify(), "")
-
-    def test_nested_inline_elements(self):
-        """Inline elements can be nested indefinitely."""
-        b_tag = "Inside a B tag"
-        self.assertSoupEquals(b_tag)
-
-        nested_b_tag = "

A nested tag

" - self.assertSoupEquals(nested_b_tag) - - double_nested_b_tag = "

A doubly nested tag

" - self.assertSoupEquals(nested_b_tag) - - def test_nested_block_level_elements(self): - """Block elements can be nested.""" - soup = self.soup('

Foo

') - blockquote = soup.blockquote - self.assertEqual(blockquote.p.b.string, 'Foo') - self.assertEqual(blockquote.b.string, 'Foo') - - def test_correctly_nested_tables(self): - """One table can go inside another one.""" - markup = ('' - '' - "') - - self.assertSoupEquals( - markup, - '
Here's another table:" - '' - '' - '
foo
Here\'s another table:' - '
foo
' - '
') - - self.assertSoupEquals( - "" - "" - "
Foo
Bar
Baz
") - - def test_multivalued_attribute_with_whitespace(self): - # Whitespace separating the values of a multi-valued attribute - # should be ignored. - - markup = '
' - soup = self.soup(markup) - self.assertEqual(['foo', 'bar'], soup.div['class']) - - # If you search by the literal name of the class it's like the whitespace - # wasn't there. - self.assertEqual(soup.div, soup.find('div', class_="foo bar")) - - def test_deeply_nested_multivalued_attribute(self): - # html5lib can set the attributes of the same tag many times - # as it rearranges the tree. This has caused problems with - # multivalued attributes. - markup = '
' - soup = self.soup(markup) - self.assertEqual(["css"], soup.div.div['class']) - - def test_multivalued_attribute_on_html(self): - # html5lib uses a different API to set the attributes ot the - # tag. This has caused problems with multivalued - # attributes. - markup = '' - soup = self.soup(markup) - self.assertEqual(["a", "b"], soup.html['class']) - - def test_angle_brackets_in_attribute_values_are_escaped(self): - self.assertSoupEquals('', '') - - def test_strings_resembling_character_entity_references(self): - # "&T" and "&p" look like incomplete character entities, but they are - # not. - self.assertSoupEquals( - "

• AT&T is in the s&p 500

", - "

\u2022 AT&T is in the s&p 500

" - ) - - def test_apos_entity(self): - self.assertSoupEquals( - "

Bob's Bar

", - "

Bob's Bar

", - ) - - def test_entities_in_foreign_document_encoding(self): - # “ and ” are invalid numeric entities referencing - # Windows-1252 characters. - references a character common - # to Windows-1252 and Unicode, and ☃ references a - # character only found in Unicode. - # - # All of these entities should be converted to Unicode - # characters. - markup = "

“Hello” -☃

" - soup = self.soup(markup) - self.assertEqual("“Hello” -☃", soup.p.string) - - def test_entities_in_attributes_converted_to_unicode(self): - expect = '

' - self.assertSoupEquals('

', expect) - self.assertSoupEquals('

', expect) - self.assertSoupEquals('

', expect) - self.assertSoupEquals('

', expect) - - def test_entities_in_text_converted_to_unicode(self): - expect = '

pi\N{LATIN SMALL LETTER N WITH TILDE}ata

' - self.assertSoupEquals("

piñata

", expect) - self.assertSoupEquals("

piñata

", expect) - self.assertSoupEquals("

piñata

", expect) - self.assertSoupEquals("

piñata

", expect) - - def test_quot_entity_converted_to_quotation_mark(self): - self.assertSoupEquals("

I said "good day!"

", - '

I said "good day!"

') - - def test_out_of_range_entity(self): - expect = "\N{REPLACEMENT CHARACTER}" - self.assertSoupEquals("�", expect) - self.assertSoupEquals("�", expect) - self.assertSoupEquals("�", expect) - - def test_multipart_strings(self): - "Mostly to prevent a recurrence of a bug in the html5lib treebuilder." - soup = self.soup("

\nfoo

") - self.assertEqual("p", soup.h2.string.next_element.name) - self.assertEqual("p", soup.p.name) - self.assertConnectedness(soup) - - def test_empty_element_tags(self): - """Verify consistent handling of empty-element tags, - no matter how they come in through the markup. - """ - self.assertSoupEquals('


', "


") - self.assertSoupEquals('


', "


") - - def test_head_tag_between_head_and_body(self): - "Prevent recurrence of a bug in the html5lib treebuilder." - content = """ - - foo - -""" - soup = self.soup(content) - self.assertNotEqual(None, soup.html.body) - self.assertConnectedness(soup) - - def test_multiple_copies_of_a_tag(self): - "Prevent recurrence of a bug in the html5lib treebuilder." - content = """ - - - - - -""" - soup = self.soup(content) - self.assertConnectedness(soup.article) - - def test_basic_namespaces(self): - """Parsers don't need to *understand* namespaces, but at the - very least they should not choke on namespaces or lose - data.""" - - markup = b'4' - soup = self.soup(markup) - self.assertEqual(markup, soup.encode()) - html = soup.html - self.assertEqual('http://www.w3.org/1999/xhtml', soup.html['xmlns']) - self.assertEqual( - 'http://www.w3.org/1998/Math/MathML', soup.html['xmlns:mathml']) - self.assertEqual( - 'http://www.w3.org/2000/svg', soup.html['xmlns:svg']) - - def test_multivalued_attribute_value_becomes_list(self): - markup = b'' - soup = self.soup(markup) - self.assertEqual(['foo', 'bar'], soup.a['class']) - - # - # Generally speaking, tests below this point are more tests of - # Beautiful Soup than tests of the tree builders. But parsers are - # weird, so we run these tests separately for every tree builder - # to detect any differences between them. - # - - def test_can_parse_unicode_document(self): - # A seemingly innocuous document... but it's in Unicode! And - # it contains characters that can't be represented in the - # encoding found in the declaration! The horror! - markup = 'Sacr\N{LATIN SMALL LETTER E WITH ACUTE} bleu!' - soup = self.soup(markup) - self.assertEqual('Sacr\xe9 bleu!', soup.body.string) - - def test_soupstrainer(self): - """Parsers should be able to work with SoupStrainers.""" - strainer = SoupStrainer("b") - soup = self.soup("A bold statement", - parse_only=strainer) - self.assertEqual(soup.decode(), "bold") - - def test_single_quote_attribute_values_become_double_quotes(self): - self.assertSoupEquals("", - '') - - def test_attribute_values_with_nested_quotes_are_left_alone(self): - text = """a""" - self.assertSoupEquals(text) - - def test_attribute_values_with_double_nested_quotes_get_quoted(self): - text = """a""" - soup = self.soup(text) - soup.foo['attr'] = 'Brawls happen at "Bob\'s Bar"' - self.assertSoupEquals( - soup.foo.decode(), - """a""") - - def test_ampersand_in_attribute_value_gets_escaped(self): - self.assertSoupEquals('', - '') - - self.assertSoupEquals( - 'foo', - 'foo') - - def test_escaped_ampersand_in_attribute_value_is_left_alone(self): - self.assertSoupEquals('') - - def test_entities_in_strings_converted_during_parsing(self): - # Both XML and HTML entities are converted to Unicode characters - # during parsing. - text = "

<<sacré bleu!>>

" - expected = "

<<sacr\N{LATIN SMALL LETTER E WITH ACUTE} bleu!>>

" - self.assertSoupEquals(text, expected) - - def test_smart_quotes_converted_on_the_way_in(self): - # Microsoft smart quotes are converted to Unicode characters during - # parsing. - quote = b"

\x91Foo\x92

" - soup = self.soup(quote) - self.assertEqual( - soup.p.string, - "\N{LEFT SINGLE QUOTATION MARK}Foo\N{RIGHT SINGLE QUOTATION MARK}") - - def test_non_breaking_spaces_converted_on_the_way_in(self): - soup = self.soup("  ") - self.assertEqual(soup.a.string, "\N{NO-BREAK SPACE}" * 2) - - def test_entities_converted_on_the_way_out(self): - text = "

<<sacré bleu!>>

" - expected = "

<<sacr\N{LATIN SMALL LETTER E WITH ACUTE} bleu!>>

".encode("utf-8") - soup = self.soup(text) - self.assertEqual(soup.p.encode("utf-8"), expected) - - def test_real_iso_latin_document(self): - # Smoke test of interrelated functionality, using an - # easy-to-understand document. - - # Here it is in Unicode. Note that it claims to be in ISO-Latin-1. - unicode_html = '

Sacr\N{LATIN SMALL LETTER E WITH ACUTE} bleu!

' - - # That's because we're going to encode it into ISO-Latin-1, and use - # that to test. - iso_latin_html = unicode_html.encode("iso-8859-1") - - # Parse the ISO-Latin-1 HTML. - soup = self.soup(iso_latin_html) - # Encode it to UTF-8. - result = soup.encode("utf-8") - - # What do we expect the result to look like? Well, it would - # look like unicode_html, except that the META tag would say - # UTF-8 instead of ISO-Latin-1. - expected = unicode_html.replace("ISO-Latin-1", "utf-8") - - # And, of course, it would be in UTF-8, not Unicode. - expected = expected.encode("utf-8") - - # Ta-da! - self.assertEqual(result, expected) - - def test_real_shift_jis_document(self): - # Smoke test to make sure the parser can handle a document in - # Shift-JIS encoding, without choking. - shift_jis_html = ( - b'
'
-            b'\x82\xb1\x82\xea\x82\xcdShift-JIS\x82\xc5\x83R\x81[\x83f'
-            b'\x83B\x83\x93\x83O\x82\xb3\x82\xea\x82\xbd\x93\xfa\x96{\x8c'
-            b'\xea\x82\xcc\x83t\x83@\x83C\x83\x8b\x82\xc5\x82\xb7\x81B'
-            b'
') - unicode_html = shift_jis_html.decode("shift-jis") - soup = self.soup(unicode_html) - - # Make sure the parse tree is correctly encoded to various - # encodings. - self.assertEqual(soup.encode("utf-8"), unicode_html.encode("utf-8")) - self.assertEqual(soup.encode("euc_jp"), unicode_html.encode("euc_jp")) - - def test_real_hebrew_document(self): - # A real-world test to make sure we can convert ISO-8859-9 (a - # Hebrew encoding) to UTF-8. - hebrew_document = b'Hebrew (ISO 8859-8) in Visual Directionality

Hebrew (ISO 8859-8) in Visual Directionality

\xed\xe5\xec\xf9' - soup = self.soup( - hebrew_document, from_encoding="iso8859-8") - # Some tree builders call it iso8859-8, others call it iso-8859-9. - # That's not a difference we really care about. - assert soup.original_encoding in ('iso8859-8', 'iso-8859-8') - self.assertEqual( - soup.encode('utf-8'), - hebrew_document.decode("iso8859-8").encode("utf-8")) - - def test_meta_tag_reflects_current_encoding(self): - # Here's the tag saying that a document is - # encoded in Shift-JIS. - meta_tag = ('') - - # Here's a document incorporating that meta tag. - shift_jis_html = ( - '\n%s\n' - '' - 'Shift-JIS markup goes here.') % meta_tag - soup = self.soup(shift_jis_html) - - # Parse the document, and the charset is seemingly unaffected. - parsed_meta = soup.find('meta', {'http-equiv': 'Content-type'}) - content = parsed_meta['content'] - self.assertEqual('text/html; charset=x-sjis', content) - - # But that value is actually a ContentMetaAttributeValue object. - self.assertTrue(isinstance(content, ContentMetaAttributeValue)) - - # And it will take on a value that reflects its current - # encoding. - self.assertEqual('text/html; charset=utf8', content.encode("utf8")) - - # For the rest of the story, see TestSubstitutions in - # test_tree.py. - - def test_html5_style_meta_tag_reflects_current_encoding(self): - # Here's the tag saying that a document is - # encoded in Shift-JIS. - meta_tag = ('') - - # Here's a document incorporating that meta tag. - shift_jis_html = ( - '\n%s\n' - '' - 'Shift-JIS markup goes here.') % meta_tag - soup = self.soup(shift_jis_html) - - # Parse the document, and the charset is seemingly unaffected. - parsed_meta = soup.find('meta', id="encoding") - charset = parsed_meta['charset'] - self.assertEqual('x-sjis', charset) - - # But that value is actually a CharsetMetaAttributeValue object. - self.assertTrue(isinstance(charset, CharsetMetaAttributeValue)) - - # And it will take on a value that reflects its current - # encoding. - self.assertEqual('utf8', charset.encode("utf8")) - - def test_python_specific_encodings_not_used_in_charset(self): - # You can encode an HTML document using a Python-specific - # encoding, but that encoding won't be mentioned _inside_ the - # resulting document. Instead, the document will appear to - # have no encoding. - for markup in [ - b'' - b'' - ]: - soup = self.soup(markup) - for encoding in PYTHON_SPECIFIC_ENCODINGS: - if encoding in ( - 'idna', 'mbcs', 'oem', 'undefined', - 'string_escape', 'string-escape' - ): - # For one reason or another, these will raise an - # exception if we actually try to use them, so don't - # bother. - continue - encoded = soup.encode(encoding) - assert b'meta charset=""' in encoded - assert encoding.encode("ascii") not in encoded - - def test_tag_with_no_attributes_can_have_attributes_added(self): - data = self.soup("text") - data.a['foo'] = 'bar' - self.assertEqual('text', data.a.decode()) - - def test_worst_case(self): - """Test the worst case (currently) for linking issues.""" - - soup = self.soup(BAD_DOCUMENT) - self.linkage_validator(soup) - - -class XMLTreeBuilderSmokeTest(object): - - def test_pickle_and_unpickle_identity(self): - # Pickling a tree, then unpickling it, yields a tree identical - # to the original. - tree = self.soup("foo") - dumped = pickle.dumps(tree, 2) - loaded = pickle.loads(dumped) - self.assertEqual(loaded.__class__, BeautifulSoup) - self.assertEqual(loaded.decode(), tree.decode()) - - def test_docstring_generated(self): - soup = self.soup("") - self.assertEqual( - soup.encode(), b'\n') - - def test_xml_declaration(self): - markup = b"""\n""" - soup = self.soup(markup) - self.assertEqual(markup, soup.encode("utf8")) - - def test_python_specific_encodings_not_used_in_xml_declaration(self): - # You can encode an XML document using a Python-specific - # encoding, but that encoding won't be mentioned _inside_ the - # resulting document. - markup = b"""\n""" - soup = self.soup(markup) - for encoding in PYTHON_SPECIFIC_ENCODINGS: - if encoding in ( - 'idna', 'mbcs', 'oem', 'undefined', - 'string_escape', 'string-escape' - ): - # For one reason or another, these will raise an - # exception if we actually try to use them, so don't - # bother. - continue - encoded = soup.encode(encoding) - assert b'' in encoded - assert encoding.encode("ascii") not in encoded - - def test_processing_instruction(self): - markup = b"""\n""" - soup = self.soup(markup) - self.assertEqual(markup, soup.encode("utf8")) - - def test_real_xhtml_document(self): - """A real XHTML document should come out *exactly* the same as it went in.""" - markup = b""" - - -Hello. -Goodbye. -""" - soup = self.soup(markup) - self.assertEqual( - soup.encode("utf-8"), markup) - - def test_nested_namespaces(self): - doc = b""" - - - - - -""" - soup = self.soup(doc) - self.assertEqual(doc, soup.encode()) - - def test_formatter_processes_script_tag_for_xml_documents(self): - doc = """ - -""" - soup = BeautifulSoup(doc, "lxml-xml") - # lxml would have stripped this while parsing, but we can add - # it later. - soup.script.string = 'console.log("< < hey > > ");' - encoded = soup.encode() - self.assertTrue(b"< < hey > >" in encoded) - - def test_can_parse_unicode_document(self): - markup = 'Sacr\N{LATIN SMALL LETTER E WITH ACUTE} bleu!' - soup = self.soup(markup) - self.assertEqual('Sacr\xe9 bleu!', soup.root.string) - - def test_popping_namespaced_tag(self): - markup = 'b2012-07-02T20:33:42Zcd' - soup = self.soup(markup) - self.assertEqual( - str(soup.rss), markup) - - def test_docstring_includes_correct_encoding(self): - soup = self.soup("") - self.assertEqual( - soup.encode("latin1"), - b'\n') - - def test_large_xml_document(self): - """A large XML document should come out the same as it went in.""" - markup = (b'\n' - + b'0' * (2**12) - + b'') - soup = self.soup(markup) - self.assertEqual(soup.encode("utf-8"), markup) - - - def test_tags_are_empty_element_if_and_only_if_they_are_empty(self): - self.assertSoupEquals("

", "

") - self.assertSoupEquals("

foo

") - - def test_namespaces_are_preserved(self): - markup = 'This tag is in the a namespaceThis tag is in the b namespace' - soup = self.soup(markup) - root = soup.root - self.assertEqual("http://example.com/", root['xmlns:a']) - self.assertEqual("http://example.net/", root['xmlns:b']) - - def test_closing_namespaced_tag(self): - markup = '

20010504

' - soup = self.soup(markup) - self.assertEqual(str(soup.p), markup) - - def test_namespaced_attributes(self): - markup = '' - soup = self.soup(markup) - self.assertEqual(str(soup.foo), markup) - - def test_namespaced_attributes_xml_namespace(self): - markup = 'bar' - soup = self.soup(markup) - self.assertEqual(str(soup.foo), markup) - - def test_find_by_prefixed_name(self): - doc = """ -foo - bar - baz - -""" - soup = self.soup(doc) - - # There are three tags. - self.assertEqual(3, len(soup.find_all('tag'))) - - # But two of them are ns1:tag and one of them is ns2:tag. - self.assertEqual(2, len(soup.find_all('ns1:tag'))) - self.assertEqual(1, len(soup.find_all('ns2:tag'))) - - self.assertEqual(1, len(soup.find_all('ns2:tag', key='value'))) - self.assertEqual(3, len(soup.find_all(['ns1:tag', 'ns2:tag']))) - - def test_copy_tag_preserves_namespace(self): - xml = """ -""" - - soup = self.soup(xml) - tag = soup.document - duplicate = copy.copy(tag) - - # The two tags have the same namespace prefix. - self.assertEqual(tag.prefix, duplicate.prefix) - - def test_worst_case(self): - """Test the worst case (currently) for linking issues.""" - - soup = self.soup(BAD_DOCUMENT) - self.linkage_validator(soup) - - -class HTML5TreeBuilderSmokeTest(HTMLTreeBuilderSmokeTest): - """Smoke test for a tree builder that supports HTML5.""" - - def test_real_xhtml_document(self): - # Since XHTML is not HTML5, HTML5 parsers are not tested to handle - # XHTML documents in any particular way. - pass - - def test_html_tags_have_namespace(self): - markup = "" - soup = self.soup(markup) - self.assertEqual("http://www.w3.org/1999/xhtml", soup.a.namespace) - - def test_svg_tags_have_namespace(self): - markup = '' - soup = self.soup(markup) - namespace = "http://www.w3.org/2000/svg" - self.assertEqual(namespace, soup.svg.namespace) - self.assertEqual(namespace, soup.circle.namespace) - - - def test_mathml_tags_have_namespace(self): - markup = '5' - soup = self.soup(markup) - namespace = 'http://www.w3.org/1998/Math/MathML' - self.assertEqual(namespace, soup.math.namespace) - self.assertEqual(namespace, soup.msqrt.namespace) - - def test_xml_declaration_becomes_comment(self): - markup = '' - soup = self.soup(markup) - self.assertTrue(isinstance(soup.contents[0], Comment)) - self.assertEqual(soup.contents[0], '?xml version="1.0" encoding="utf-8"?') - self.assertEqual("html", soup.contents[0].next_element.name) - -def skipIf(condition, reason): - def nothing(test, *args, **kwargs): - return None - - def decorator(test_item): - if condition: - return nothing - else: - return test_item - - return decorator diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4/tests/__init__.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4/tests/__init__.py deleted file mode 100644 index 142c8cc..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4/tests/__init__.py +++ /dev/null @@ -1 +0,0 @@ -"The beautifulsoup tests." diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4/tests/__pycache__/__init__.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4/tests/__pycache__/__init__.cpython-38.pyc deleted file mode 100644 index 92916ff..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4/tests/__pycache__/__init__.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4/tests/__pycache__/test_builder_registry.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4/tests/__pycache__/test_builder_registry.cpython-38.pyc deleted file mode 100644 index 20e8328..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4/tests/__pycache__/test_builder_registry.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4/tests/__pycache__/test_docs.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4/tests/__pycache__/test_docs.cpython-38.pyc deleted file mode 100644 index 73a8066..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4/tests/__pycache__/test_docs.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4/tests/__pycache__/test_html5lib.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4/tests/__pycache__/test_html5lib.cpython-38.pyc deleted file mode 100644 index f83a594..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4/tests/__pycache__/test_html5lib.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4/tests/__pycache__/test_htmlparser.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4/tests/__pycache__/test_htmlparser.cpython-38.pyc deleted file mode 100644 index bc6168b..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4/tests/__pycache__/test_htmlparser.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4/tests/__pycache__/test_lxml.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4/tests/__pycache__/test_lxml.cpython-38.pyc deleted file mode 100644 index a78f33c..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4/tests/__pycache__/test_lxml.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4/tests/__pycache__/test_soup.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4/tests/__pycache__/test_soup.cpython-38.pyc deleted file mode 100644 index 9aacb27..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4/tests/__pycache__/test_soup.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4/tests/__pycache__/test_tree.cpython-38.pyc b/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4/tests/__pycache__/test_tree.cpython-38.pyc deleted file mode 100644 index 0912721..0000000 Binary files a/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4/tests/__pycache__/test_tree.cpython-38.pyc and /dev/null differ diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4/tests/test_builder_registry.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4/tests/test_builder_registry.py deleted file mode 100644 index 90cad82..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4/tests/test_builder_registry.py +++ /dev/null @@ -1,147 +0,0 @@ -"""Tests of the builder registry.""" - -import unittest -import warnings - -from bs4 import BeautifulSoup -from bs4.builder import ( - builder_registry as registry, - HTMLParserTreeBuilder, - TreeBuilderRegistry, -) - -try: - from bs4.builder import HTML5TreeBuilder - HTML5LIB_PRESENT = True -except ImportError: - HTML5LIB_PRESENT = False - -try: - from bs4.builder import ( - LXMLTreeBuilderForXML, - LXMLTreeBuilder, - ) - LXML_PRESENT = True -except ImportError: - LXML_PRESENT = False - - -class BuiltInRegistryTest(unittest.TestCase): - """Test the built-in registry with the default builders registered.""" - - def test_combination(self): - if LXML_PRESENT: - self.assertEqual(registry.lookup('fast', 'html'), - LXMLTreeBuilder) - - if LXML_PRESENT: - self.assertEqual(registry.lookup('permissive', 'xml'), - LXMLTreeBuilderForXML) - self.assertEqual(registry.lookup('strict', 'html'), - HTMLParserTreeBuilder) - if HTML5LIB_PRESENT: - self.assertEqual(registry.lookup('html5lib', 'html'), - HTML5TreeBuilder) - - def test_lookup_by_markup_type(self): - if LXML_PRESENT: - self.assertEqual(registry.lookup('html'), LXMLTreeBuilder) - self.assertEqual(registry.lookup('xml'), LXMLTreeBuilderForXML) - else: - self.assertEqual(registry.lookup('xml'), None) - if HTML5LIB_PRESENT: - self.assertEqual(registry.lookup('html'), HTML5TreeBuilder) - else: - self.assertEqual(registry.lookup('html'), HTMLParserTreeBuilder) - - def test_named_library(self): - if LXML_PRESENT: - self.assertEqual(registry.lookup('lxml', 'xml'), - LXMLTreeBuilderForXML) - self.assertEqual(registry.lookup('lxml', 'html'), - LXMLTreeBuilder) - if HTML5LIB_PRESENT: - self.assertEqual(registry.lookup('html5lib'), - HTML5TreeBuilder) - - self.assertEqual(registry.lookup('html.parser'), - HTMLParserTreeBuilder) - - def test_beautifulsoup_constructor_does_lookup(self): - - with warnings.catch_warnings(record=True) as w: - # This will create a warning about not explicitly - # specifying a parser, but we'll ignore it. - - # You can pass in a string. - BeautifulSoup("", features="html") - # Or a list of strings. - BeautifulSoup("", features=["html", "fast"]) - - # You'll get an exception if BS can't find an appropriate - # builder. - self.assertRaises(ValueError, BeautifulSoup, - "", features="no-such-feature") - -class RegistryTest(unittest.TestCase): - """Test the TreeBuilderRegistry class in general.""" - - def setUp(self): - self.registry = TreeBuilderRegistry() - - def builder_for_features(self, *feature_list): - cls = type('Builder_' + '_'.join(feature_list), - (object,), {'features' : feature_list}) - - self.registry.register(cls) - return cls - - def test_register_with_no_features(self): - builder = self.builder_for_features() - - # Since the builder advertises no features, you can't find it - # by looking up features. - self.assertEqual(self.registry.lookup('foo'), None) - - # But you can find it by doing a lookup with no features, if - # this happens to be the only registered builder. - self.assertEqual(self.registry.lookup(), builder) - - def test_register_with_features_makes_lookup_succeed(self): - builder = self.builder_for_features('foo', 'bar') - self.assertEqual(self.registry.lookup('foo'), builder) - self.assertEqual(self.registry.lookup('bar'), builder) - - def test_lookup_fails_when_no_builder_implements_feature(self): - builder = self.builder_for_features('foo', 'bar') - self.assertEqual(self.registry.lookup('baz'), None) - - def test_lookup_gets_most_recent_registration_when_no_feature_specified(self): - builder1 = self.builder_for_features('foo') - builder2 = self.builder_for_features('bar') - self.assertEqual(self.registry.lookup(), builder2) - - def test_lookup_fails_when_no_tree_builders_registered(self): - self.assertEqual(self.registry.lookup(), None) - - def test_lookup_gets_most_recent_builder_supporting_all_features(self): - has_one = self.builder_for_features('foo') - has_the_other = self.builder_for_features('bar') - has_both_early = self.builder_for_features('foo', 'bar', 'baz') - has_both_late = self.builder_for_features('foo', 'bar', 'quux') - lacks_one = self.builder_for_features('bar') - has_the_other = self.builder_for_features('foo') - - # There are two builders featuring 'foo' and 'bar', but - # the one that also features 'quux' was registered later. - self.assertEqual(self.registry.lookup('foo', 'bar'), - has_both_late) - - # There is only one builder featuring 'foo', 'bar', and 'baz'. - self.assertEqual(self.registry.lookup('foo', 'bar', 'baz'), - has_both_early) - - def test_lookup_fails_when_cannot_reconcile_requested_features(self): - builder1 = self.builder_for_features('foo', 'bar') - builder2 = self.builder_for_features('foo', 'baz') - self.assertEqual(self.registry.lookup('bar', 'baz'), None) diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4/tests/test_docs.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4/tests/test_docs.py deleted file mode 100644 index 5b9f677..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4/tests/test_docs.py +++ /dev/null @@ -1,36 +0,0 @@ -"Test harness for doctests." - -# pylint: disable-msg=E0611,W0142 - -__metaclass__ = type -__all__ = [ - 'additional_tests', - ] - -import atexit -import doctest -import os -#from pkg_resources import ( -# resource_filename, resource_exists, resource_listdir, cleanup_resources) -import unittest - -DOCTEST_FLAGS = ( - doctest.ELLIPSIS | - doctest.NORMALIZE_WHITESPACE | - doctest.REPORT_NDIFF) - - -# def additional_tests(): -# "Run the doc tests (README.txt and docs/*, if any exist)" -# doctest_files = [ -# os.path.abspath(resource_filename('bs4', 'README.txt'))] -# if resource_exists('bs4', 'docs'): -# for name in resource_listdir('bs4', 'docs'): -# if name.endswith('.txt'): -# doctest_files.append( -# os.path.abspath( -# resource_filename('bs4', 'docs/%s' % name))) -# kwargs = dict(module_relative=False, optionflags=DOCTEST_FLAGS) -# atexit.register(cleanup_resources) -# return unittest.TestSuite(( -# doctest.DocFileSuite(*doctest_files, **kwargs))) diff --git a/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4/tests/test_html5lib.py b/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4/tests/test_html5lib.py deleted file mode 100644 index b77659b..0000000 --- a/Jobs_Collections/venv/Lib/python3.8/site-packages/bs4/tests/test_html5lib.py +++ /dev/null @@ -1,190 +0,0 @@ -"""Tests to ensure that the html5lib tree builder generates good trees.""" - -import warnings - -try: - from bs4.builder import HTML5TreeBuilder - HTML5LIB_PRESENT = True -except ImportError as e: - HTML5LIB_PRESENT = False -from bs4.element import SoupStrainer -from bs4.testing import ( - HTML5TreeBuilderSmokeTest, - SoupTest, - skipIf, -) - -@skipIf( - not HTML5LIB_PRESENT, - "html5lib seems not to be present, not testing its tree builder.") -class HTML5LibBuilderSmokeTest(SoupTest, HTML5TreeBuilderSmokeTest): - """See ``HTML5TreeBuilderSmokeTest``.""" - - @property - def default_builder(self): - return HTML5TreeBuilder - - def test_soupstrainer(self): - # The html5lib tree builder does not support SoupStrainers. - strainer = SoupStrainer("b") - markup = "

A bold statement.

" - with warnings.catch_warnings(record=True) as w: - soup = self.soup(markup, parse_only=strainer) - self.assertEqual( - soup.decode(), self.document_for(markup)) - - self.assertTrue( - "the html5lib tree builder doesn't support parse_only" in - str(w[0].message)) - - def test_correctly_nested_tables(self): - """html5lib inserts tags where other parsers don't.""" - markup = ('' - '' - "') - - self.assertSoupEquals( - markup, - '
Here's another table:" - '' - '' - '
foo
Here\'s another table:' - '
foo
' - '
') - - self.assertSoupEquals( - "" - "" - "
Foo
Bar
Baz
") - - def test_xml_declaration_followed_by_doctype(self): - markup = ''' - - - - - -

foo

- -''' - soup = self.soup(markup) - # Verify that we can reach the

tag; this means the tree is connected. - self.assertEqual(b"

foo

", soup.p.encode()) - - def test_reparented_markup(self): - markup = '

foo

\n

bar

' - soup = self.soup(markup) - self.assertEqual("

foo

\n

bar

", soup.body.decode()) - self.assertEqual(2, len(soup.find_all('p'))) - - - def test_reparented_markup_ends_with_whitespace(self): - markup = '

foo

\n

bar

\n' - soup = self.soup(markup) - self.assertEqual("

foo

\n

bar

\n", soup.body.decode()) - self.assertEqual(2, len(soup.find_all('p'))) - - def test_reparented_markup_containing_identical_whitespace_nodes(self): - """Verify that we keep the two whitespace nodes in this - document distinct when reparenting the adjacent tags. - """ - markup = '
' - soup = self.soup(markup) - space1, space2 = soup.find_all(string=' ') - tbody1, tbody2 = soup.find_all('tbody') - assert space1.next_element is tbody1 - assert tbody2.next_element is space2 - - def test_reparented_markup_containing_children(self): - markup = '' - soup = self.soup(markup) - noscript = soup.noscript - self.assertEqual("target", noscript.next_element) - target = soup.find(string='target') - - # The 'aftermath' string was duplicated; we want the second one. - final_aftermath = soup.find_all(string='aftermath')[-1] - - # The