python |
Pythonタグが付けられた新着投稿 - Qiita |
オフライン環境構築 pip編 |
https://qiita.com/kannkyo/items/aca48ed928a433c7ca4c
|
実行環境に適したwheelパッケージsdistパッケージpipdownloadの仕組みpipにはパッケージをインストールせず、ダウンロードだけするサブコマンドpipdownloadが用意されています。 |
2021-08-21 18:58:29 |
python |
Pythonタグが付けられた新着投稿 - Qiita |
Pythonで感情極性辞書を用いたテキスト感情分析をつくってみた |
https://qiita.com/miso_taku/items/c8e48401346eca23bae8
|
内容としてはjanomeを使って形態素解析で取り出した単語を辞書で引いて感情値を取得し平均を取って戻り値で返します。 |
2021-08-21 18:38:41 |
js |
JavaScriptタグが付けられた新着投稿 - Qiita |
ES6メソッドの復習 map(), filter(), findIndex(), test() |
https://qiita.com/YSasago/items/ac06586ed61dde6e4a8b
|
|
2021-08-21 18:35:22 |
Program |
[全てのタグ]の新着質問一覧|teratail(テラテイル) |
【Rails】Wheneverを使ってRakeタスクを定期実行できないです |
https://teratail.com/questions/355436?rss=all
|
【Rails】Wheneverを使ってRakeタスクを定期実行できないです前提・実現したいことWheneverを使ってRakeタスクを定期実行したいです。 |
2021-08-21 18:41:17 |
Program |
[全てのタグ]の新着質問一覧|teratail(テラテイル) |
スライドが全て表示されてしまう |
https://teratail.com/questions/355435?rss=all
|
スライドが全て表示されてしまうワードプレスの教本をもとにサンプルサイトを作成しておりますが、トップ画面のスライドショーがうまく表示されません。 |
2021-08-21 18:39:25 |
Program |
[全てのタグ]の新着質問一覧|teratail(テラテイル) |
UnityUIでScrollViewの中身をアタッチできない |
https://teratail.com/questions/355434?rss=all
|
UnityUIでScrollViewの中身をアタッチできない前提・実現したいことScrollViewにGridLayoutGroupを使って、画像などを等間隔に表示したスクロールバーを作成しようとしています。 |
2021-08-21 18:37:25 |
Program |
[全てのタグ]の新着質問一覧|teratail(テラテイル) |
スプレッドシート関数 |
https://teratail.com/questions/355433?rss=all
|
関数 |
2021-08-21 18:27:00 |
Program |
[全てのタグ]の新着質問一覧|teratail(テラテイル) |
Web上にアップしたExcelやWordのファイルを共同編集するには? |
https://teratail.com/questions/355432?rss=all
|
Web上にアップしたExcelやWordのファイルを共同編集するにはMicrosoftのOneDriveやサードパーティのサービスで、WebにアップロードしたExcelやWordファイルを、手元のパソコンにインストールしたExcel、Wordで編集することができます。 |
2021-08-21 18:11:55 |
Ruby |
Rubyタグが付けられた新着投稿 - Qiita |
1周目 railsチュートリアル第5章 |
https://qiita.com/ak-matsu/items/ba79cfc46793e5432561
|
第引数オプションハッシュ上記ではcssidのlogoを指定。 |
2021-08-21 18:10:53 |
Docker |
dockerタグが付けられた新着投稿 - Qiita |
[dokuwiki] dokuwikiの引越し |
https://qiita.com/robozushi10/items/4c5eed939f51eb326bc2
|
|
2021-08-21 18:46:58 |
Git |
Gitタグが付けられた新着投稿 - Qiita |
【Git】Pushし忘れでリモートとローカルが乖離してしまった話 |
https://qiita.com/nao0725/items/2ffe9ac390ac9b7e9201
|
実行は気をつけてください、、、実行内容はこちら差分を改めて修正修正後、developにpushしてからmainにマージする投稿者コメント今回も戒めをこめて記事にしました、、、ゼッタイPushしましょう、、、MyProfileプログラミング学習歴ヶ月目のアカウントですプログラミングスクールで学んだ内容や自分が躓いた箇所等のアウトプットの為に発信しています。 |
2021-08-21 18:50:57 |
技術ブログ |
Mercari Engineering Blog |
All for Oneでたのしいおさわりかいをするよ! |
https://engineering.mercari.com/blog/entry/20210821-osawarikai/
|
hellip |
2021-08-21 10:00:14 |
技術ブログ |
Developers.IO |
CloudWatch ダッシュボードで値の低いメトリクスが下に張り付くときの対処方法 |
https://dev.classmethod.jp/articles/tsnote-cloudwatch-dashboard-separate-axis-y/
|
cloudwatch |
2021-08-21 09:13:55 |
海外TECH |
DEV Community |
⚡ How to skip Chromium download in Puppeteer? |
https://dev.to/maxprogramming/how-to-skip-chromium-download-in-puppeteer-2c24
|
How to skip Chromium download in Puppeteer Hello again If you re a Node js developer and you ve used Puppeteer for web scraping you might have seen that it downloads Chromium whenever you install puppeteer Many of you people don t like to download an external web browser for this You might have Chrome Edge Brave or any other Chromium based browser on your system so why not use that Step Set the environment variablesWhenever you install Puppeteer it will first check for the environment variables listed below Read more on DevDocs environment variablesWe are interested in PUPPETEER SKIP CHROMIUM DOWNLOAD and PUPPETEER EXECUTABLE PATH In your operating system you have to set these two environment variables to these values KeyValuePUPPETEER SKIP CHROMIUM DOWNLOADtruePUPPETEER EXECUTABLE PATH PATH TO CHROME OR CHROMIUM On WindowsSearch this term Edit the system environment variables in Start Menu and open itClick this button on the bottom right Click on the New button under System variables Enter the variable name and value as given below KeyValuePUPPETEER SKIP CHROMIUM DOWNLOADtruePUPPETEER EXECUTABLE PATH PATH TO CHROME OR CHROMIUM Find browser s pathThe simplest way to find the path to your browser s executable on Windows is to right click the shortcut on the desktop and click on Open file location In my case I used Microsoft Edge so this was the path C Program Files x Microsoft Edge Application msedge exeIt ll take you to the file location and you can copy the path and paste it into the environment variables Thanks for reading I hope you liked it Comment down your thoughts There is always room for improvement so let me know your suggestions Connect with me on my YouTube channel and my Twitter Until next time keeping awesome ️ |
2021-08-21 09:47:15 |
海外TECH |
DEV Community |
Vue Academy #5: Communication between components |
https://dev.to/codeozz/vue-academy-5-communication-between-components-4d53
|
Vue Academy Communication between componentsWhen you pass props from parent to children you might need to update this data In vuejs you have two ways to handle this case the most used is to emit an event from the children to the parent The other way is to use bus event Emit event from childrenIn component paradigm we have a component in the component in component From one parent you can pass multiple data in another child component called props In some cases you will need to update these props from one of these child components Should you update these props directly NO If you try to make this on a props object vue will trigger a warn about this manipulation You mustn t DO this ️Mutating props like this is considered to be an anti pattern Two rules Only the component can change its stateOnly the parent of the component can change the propsSo how can you update the props from children properly Use emit event Emit an event from the child component with the new value to update the props in this event Handle this event in the parent and update the data A short example Context We need to update props when clicking onChild vue lt template gt lt div gt lt When we click on button we want to update value gt lt button click updateCounter counter gt lt div gt lt template gt lt script gt import Vue from vue export default Vue extend props counter Number methods updateCounter newValue Emit event from child with the new value this emit update counter newValue lt script gt Parent vue lt template gt lt div gt lt child counter counter lt We handle the update event and we update the current props value gt update counter counter event gt lt div gt lt template gt lt script gt import Vue from vue We omit Child component importexport default Vue extend components Child data return counter lt script gt As you can see it can be easy to update props value from children If you have more deep children like this Parent gt Child one gt Child TwoChild two has two parents Parent and Child One If you need to update props from Child two you can emit an event to Child One and emit another event to Parent In general this tip is efficient but in some cases you will need to communicate from one component to another component that is not linked by parent for example imagine that your Footer needs to communicate with your Header You cannot emit events between them How to handle this Bus EventVue allows us to use bus events It s a way to emit data between both components without using Parent First we need to create our bus event import Vue from vue import App from App vue export const bus new Vue new Vue render h gt h App mount app Footer vue lt script gt import Vue from vue We omit template and bus importexport default Vue extend methods emitValueWithBus value Emit value thanks to the bus bus emit update value toto lt script gt Header vue lt script gt import Vue from vue We omit template and bus importexport default Vue extend Init the bus connection when created component created Get value from event with the bus event bus on update value data gt data is equal to toto destroyed When component is destroyed we should remove listener bus off lt script gt Note We remove listener manually vue handle this case for bus event automatically ConclusionAs we have seen before if you need to update props value you need to handle it in the parent component thanks to event But in some cases we can t use these tips so we need to use the event bus If you want to have nice article to read about web dev you can subscribe to my FREE newsletter at this url gt And you can follow me on Twitter Github And if you want to buy me a coffee D gt |
2021-08-21 09:34:43 |
海外TECH |
DEV Community |
Learning Python- Intermediate course: Day 12, Summary of the week |
https://dev.to/aatmaj/learning-python-intermediate-course-day-12-random-numbers-2097
|
Learning Python Intermediate course Day Summary of the week Today let us revise whatever we have learnt so far in this week Summary of the week Day Complex numbers part In this part we explored the cmath module The cmath module in Python s a built in module which contains mathematical functions related to operations of complex numbers Complex numbers can be created in the following manner z complex x y z real and z imaginary provide us with the real and imaginary parts We also saw how easily we can operate complex numbers in Python We can do operations like addition product and raising to a power simply with the use of operators Unlike other languages we do not require any other functions for these simple operations Day Complex numbers part This part was reserved for cmath module functions We covered functions like phase and polar which are frequently used while operating with complex numbers After that we saw how we can use the methods in the cmath library for more complicated mathematical operations Entire list of functions with documentation can be found hereComplex numbers are useful in many branches of programming We checked out a few in this part For those who are not comfortable with the use of complex numbers might like this video series Day Random numbersIn this part we focused on the Python random module Just like the math and cmath modules the random module is built in into Python so we do not need to take any extra efforts to download or install it We saw how to cover complex numbers in the range by using the random method The randint method generates a integer between a given range of numbers We also covered methods to return a list of random numbers Thank you That was all for this week Meet you next Tuesday For those who have not yet made account in Dev to you can have a free easy sign up using your mail or GitHub accounts I would suggest the budding developers to create your GitHub free account right away You would require to register sooner or later anywaysFollow me on GitHub for updates |
2021-08-21 09:15:22 |
海外TECH |
DEV Community |
What if Python Had This Ruby Feature? |
https://dev.to/miguendes/what-if-python-had-this-ruby-feature-33p
|
What if Python Had This Ruby Feature In this post I ll present how I changed Python to accept else less if expressions similar to Ruby s inline if also known as conditional modifier Why The idea of having an else less if expression in Python came to my mind when I had to work with a Ruby service at my past job Ruby contrary to Python makes lots of things implicit Citation needed and this kind of if expression is one of them I say it s implicit because it returns nil if the expression evaluates to false This is also called conditional modifier irbirb main gt RUBY VERSION gt irb main gt a if true gt irb main gt b if false gt nilirb main gt b gt nilirb main gt a gt In Python one cannot do that without explicitly adding an else to the expression In fact as of this PR the interpreter will tell right away that the else is mandatory in the SyntaxError message pythonPython a heads main ebfa Aug GCC on linuxType help copyright credits or license for more information gt gt gt a if True File lt stdin gt line a if True SyntaxError expected else after if expressionHowever I find Ruby s if actually very convenient This convenience became more evident when I had to go back to Python and write things like this gt gt gt my var if some cond else NoneSo I thought to myself what would be like if Python had similar feature Could I do it myself How hard would that be How Me trying to make sense of CPython s source code Digging into CPython s code and changing the language s syntax sounded not trivial to me Luckily during the same week I found out on Twitter that Anthony Shaw had just written a book on CPython Internals and it was available for pre release I didn t think twice and bought the book I ve got to be honest I m the kind of person who buys things and doesn t use them immediately As I had other plans in mind I let it getting dust in my home folder for a while Until I had to work with that Ruby service again It reminded me of the CPython Internals book and how challenging hacking the guts of Python would be First thing was to go though the book from the very start and try to follow each step The book focus on Python so in order to follow though it one needs to checkout the tag and that s what I did I learned about how the code is structured and then how to compile it The next chapters show how to extend the grammar and add new things such as a new operator As I got familiar with the code base and how to tweak the grammar I decided to give it a spin and make my own changes to it The First Failed AttemptAs I started finding my way around CPython s code from the latest main branch I noticed that lots of things had changed since Python yet some fundamental concepts didn t My first shot was to dig into the grammar definition and find the if expression rule The file is currently named Grammar python gram Locating it was not difficult an ordinary CTRL F for the else keyword was enough file Grammar python gram expression expr ty memo invalid expression a disjunction if b disjunction else c expression PyAST IfExp b a c EXTRA disjunction lambdef Now with the rule in hand my idea was to add one more option to the current if expression where it would match a disjunction if b disjunction and c expression would be NULL This new rule should be placed immediately after the complete one otherwise the parser would match a disjunction if b disjunction always returning a SyntaxError expression expr ty memo invalid expression a disjunction if b disjunction else c expression PyAST IfExp b a c EXTRA a disjunction if b disjunction PyAST IfExp b a NULL EXTRA disjunction lambdef Regenerating the Parser and Compiling Python From SourceCPython comes with a Makefile containing lots of useful commands One of them is the regen pegen command which converts Grammar python gram into Parser parser c Besides changing the grammar I had to modify the AST for the if expression AST stands for Abstract Syntax Tree and it is a way of representing the syntactic structure of the grammar as a tree For a more information about ASTs I highly recommend the Crafting Interpreters book by Robert Nystrom Moving on if you observe the rule for if expression goes like this a disjunction if b disjunction else c expression PyAST IfExp b a c EXTRA The means when the parser finds this rule it calls the PyAST IfExp which gives back a expr ty data structure So this gave me a clue in order to implement the behavior of the new rule I d need to change PyAST IfExp To find where is located I used my rip grep skills and searched for it inside the source root rg PyAST IfExp C OMITTED Python Python ast c expr ty PyAST IfExp expr ty test expr ty body expr ty orelse int lineno int col offset int end lineno int end col offset PyArena arena OMITTED And the implementation goes like this expr ty PyAST IfExp expr ty test expr ty body expr ty orelse int lineno int col offset int end lineno int end col offset PyArena arena expr ty p if test PyErr SetString PyExc ValueError field test is required for IfExp return NULL if body PyErr SetString PyExc ValueError field body is required for IfExp return NULL if orelse PyErr SetString PyExc ValueError field orelse is required for IfExp return NULL p expr ty PyArena Malloc arena sizeof p if p return NULL p gt kind IfExp kind p gt v IfExp test test p gt v IfExp body body p gt v IfExp orelse orelse p gt lineno lineno p gt col offset col offset p gt end lineno end lineno p gt end col offset end col offset return p Since I pass orelse as NULL I thought it was just a matter of changing the body of if orelse and assign None to orelse if orelse PyErr SetString PyExc ValueError field orelse is required for IfExp return NULL orelse Py None Now time to test it I compile the code with make j s and fire up the interpreter make j s Python Python ast c In function PyAST IfExp Python Python ast c warning assignment from incompatible pointer type Wincompatible pointer types orelse Py None Despite the glaring obvious warnings I decided to ignore it just to see what happens pythonPython a heads ruby if new dirty fbef Aug GCC on linuxType help copyright credits or license for more information gt gt gt a if True gt gt gt a gt gt gt b if False segmentation fault core dumped pythonOuch It works for the if True case but assigning Py None to expr ty orelse causes a segfault Time to go back to see what is wrong The Second AttemptIt wasn t too difficult to figure out where I messed up orelse is a expr ty and I m assigning to it a Py None which is a PyObject Again thanks to rip grep I found its definition rg constant tc CInclude internal pycore asdl h typedef PyObject string typedef PyObject object typedef PyObject constant Now how did I find out Py None was a constant Whilst reviewing Grammar python gram file I found that one of the rules for the new pattern matching syntax is defined like this Literal patterns are used for equality and identity constraintsliteral pattern pattern ty value signed number PyAST MatchValue value EXTRA value complex number PyAST MatchValue value EXTRA value strings PyAST MatchValue value EXTRA None PyAST MatchSingleton Py None EXTRA However this rule is a pattern ty not an expr ty But that s fine What really matters is to understand what PyAST MatchSingleton actually is Then I searched for it in Python Python ast c file Python Python ast c pattern ty PyAST MatchSingleton constant value int lineno int col offset int end lineno int end col offset PyArena arena Now back to the drawing board I look for the definition of a None node in the grammar To my great relief I find it atom expr ty NAME True PyAST Constant Py True NULL EXTRA False PyAST Constant Py False NULL EXTRA None PyAST Constant Py None NULL EXTRA At this point I had all the information I needed To return a expr ty representing None I need to create a node in the AST which is constant by using the PyAST Constant function a disjunction if b disjunction else c expression PyAST IfExp b a c EXTRA a disjunction if b disjunction PyAST IfExp b a NULL EXTRA a disjunction if b disjunction PyAST IfExp b a PyAST Constant Py None NULL EXTRA EXTRA disjunctionNow I must revert Python Python ast c as well Since I m feeding it a valid expr ty it will never be NULL file Python Python ast c if orelse orelse Py None PyErr SetString PyExc ValueError field orelse is required for IfExp return NULL Let s compile it again and see what happens make j s amp amp python Python a heads ruby if new dirty cebef Aug GCC on linuxType help copyright credits or license for more information gt gt gt c if True gt gt gt c gt gt gt b if False gt gt gt type b lt class NoneType gt gt gt gt WOT It works Now we need to do one more test Ruby functions allow returning a value if a condition matches and if not the rest of the function body gets executed Like this At this point I wonder if that would work out of the box I rush to the interpreter again and write the same function gt gt gt def f test return if test print missed return return gt gt gt f False gt gt gt f True gt gt gt Ooopss The function returns None if test is False To help me debug this I summoned the ast module The official docs define it like so The ast module helps Python applications to process trees of the Python abstract syntax grammar The abstract syntax itself might change with each Python release this module helps to find out programmatically what the current grammar looks like Let s print the AST for this function gt gt gt fc def f test return if test print missed return return gt gt gt print ast dump ast parse fc indent Module body FunctionDef name f args arguments posonlyargs args arg arg test kwonlyargs kw defaults defaults body Return value IfExp test Name id test ctx Load body Constant value orelse Constant value None Expr value Call func Name id print ctx Load args Constant value missed return keywords Return value Constant value decorator list type ignores Now things make more sense my change to the grammar was just a syntax sugar It turns an expression like this a if b into this a if b else None The problem here is that Python will return no matter what so the rest of the function is ignored We can also look at the bytecode generated to understand what exactly is executed by the interpreter And for that we can use the dis module According to the docs The dis module supports the analysis of CPython bytecode by disassembling it gt gt gt import dis gt gt gt dis dis f LOAD FAST test POP JUMP IF FALSE to LOAD CONST RETURN VALUE gt gt LOAD CONST None RETURN VALUEWhat this basically means is that in case the test is false the execution jumps to which loads the None into the top of the stack and returns it Supporting return if To support the same Ruby feature I can turn the expression return if test into a regular if statement that returns if test is true To do that I needed to add one more rule This time it would be a rule that matches the return lt value gt if lt test gt piece of code Not only that we need a PyAST function that creates the node for us Let s then call it PyAST ReturnIfExpr file Grammar python gramreturn stmt stmt ty return a star expressions if b disjunction PyAST ReturnIfExpr a b EXTRA return a star expressions PyAST Return a EXTRA As mentioned previously the implementation for all these functions reside in Python Python ast c and the their definition in Include internal pycore ast h so I put PyAST ReturnIfExpr there file Include internal pycore ast h stmt ty PyAST Return expr ty value int lineno int col offset int end lineno int end col offset PyArena arena stmt ty PyAST ReturnIfExpr expr ty value expr ty test int lineno int col offset int end lineno int end col offset PyArena arena stmt ty PyAST Delete asdl expr seq targets int lineno int col offset int end lineno int end col offset PyArena arena file Python Python ast c stmt ty PyAST ReturnIfExpr expr ty value expr ty test int lineno int col offset int end lineno int end col offset PyArena arena stmt ty ret p ret PyAST Return value lineno col offset end lineno end col offset arena asdl stmt seq body body Py asdl stmt seq new arena asdl seq SET body ret p PyAST If test body NULL lineno col offset end lineno end col offset arena return p stmt tyLet s pause for a bit to examine the implementation of PyAST ReturnIfExpr Like I mentioned previously I want to turn return lt value gt if lt test gt into if lt test gt return lt value gt Both return and the regular if are statements so in CPython they re represented as stmt ty The PyAST If expectes a expr ty test and a body which is a sequence of statements In this case body is asdl stmt seq body As a result what we really want here is a if statement with a body where the only statement is a return lt value gt one CPython disposes of some convenient functions to build asdl stmt seq and one of them is Py asdl stmt seq new So I used it to create the body and add the return statement I created a few lines before with PyAST Return Once that s done the last step is to pass the test as well as the body to PyAST If And before I forget you may be wondering what on earth is the PyArena arena Arena is a CPython abstraction used for memory allocation It allows efficient memory usage by using memory mapping mmap and placing them in contiguous chunks of memory reference Now it s time to regenerate the parser and test it one more time gt gt gt def f test return if test print missed return return gt gt gt import dis gt gt gt f False gt gt gt f True Oh no It doesn t work Let s check the bytecodes gt gt gt dis dis f LOAD FAST test POP JUMP IF FALSE to LOAD CONST RETURN VALUE gt gt LOAD CONST None RETURN VALUE gt gt gt the same bloody bytecode instructions again Going Back to the Compilers ClassAt that point I was clueless I had no idea what was going on until I decided to go down the rabbit hole of expanding the grammar rules The new rule I added went like this return a star expressions if b disjunction PyAST ReturnIfExpr a b EXTRA My only hypothesis is that a star expressions if b disjunction is being resolved to the else less rule I added in the beginning By going over the grammar one more time I figure that my theory holds star expressions will match a disjunction if b disjunction PyAST IfExp b a NULL EXTRA The only way to fix this is by getting rid of the star expressions So I change the rule to return stmt stmt ty return a star expressions if b disjunction PyAST ReturnIfExpr a b EXTRA return a disjunction guard guard else PyAST ReturnIfExpr a guard EXTRA return a star expressions PyAST Return a EXTRA You might be wondering what is guard and what is else and what is star expressions This guard is a rule that is part of the pattern matching rules The new pattern matching feature added in Python allows things like this match point case Point x y if x y print f Y X at x case Point x y print f Not on the diagonal And the rule goes by this guard expr ty if guard named expression guard With that I added one more check To avoid it failing with SyntaxError we need to make sure the rule matches only code like this return value if cond Thus to prevent code such as return an if cond else b being matched prematurely I added a else to the rule Last but not least the star expressions allow us to return to return destructured iterables For example gt gt gt def f a return a gt gt gt f In this case a is a tuple which falls under the category of star expressions The regular if expression doesn t allow using star expressions with it AFAIK so changing our new return rule won t be an issue Does it work yet After fixing the return rule I regenerate the grammar one more time and compile it gt gt gt def f test return if test print missed return return gt gt gt f False missed return gt gt gt f True And IT WORKS Let s check the bytecode then gt gt gt import dis gt gt gt dis dis f LOAD FAST test POP JUMP IF FALSE to LOAD CONST RETURN VALUE gt gt LOAD GLOBAL print LOAD CONST missed return CALL FUNCTION POP TOP LOAD CONST RETURN VALUE gt gt gt That s precisely what I wanted In fact to make sure let also see if the AST is the same as the one with regular if gt gt gt import ast gt gt gt print ast dump ast parse fc indent Module body FunctionDef name f args arguments posonlyargs args arg arg test kwonlyargs kw defaults defaults body If test Name id test ctx Load body Return value Constant value orelse Expr value Call func Name id print ctx Load args Constant value missed return keywords Return value Constant value decorator list type ignores gt gt gt And indeed it is If test Name id test ctx Load body Return value Constant value orelse This node is the same as the one that would be generated byif test return If It s Not Tested It s Broken To conclude this journey I thought it d be a good idea to add some unit tests as well Before writing anything new I wanted to get an idea of what I had broken With the code tested manually I run all tests using the test module python m test j The j means we ll use processes to run the tests in parallel python m test jTo my surprise only one test fail Tests result FAILURE tests OK test failed test grammarSince I ran all tests it s hard to navigate on the output so I can run only this one again in isolation FAIL test listcomps test test grammar GrammarTests Traceback most recent call last File home miguel projects cpython Lib test test grammar py line in test listcomps check syntax error self x if y File home miguel projects cpython Lib test support init py line in check syntax error with testcase assertRaisesRegex SyntaxError errtext as cm AssertionError SyntaxError not raised Ran tests in sFAILED failures test test grammar failedtest grammar failed failure Tests result FAILURE test failed test grammar re run test test grammarTotal duration msTests result FAILUREAnd there it is It expects a syntax error when running a x if y expression We can safely remove it and re run the tests again Tests result SUCCESS test OK Total duration msTests result SUCCESSNow that everything is OK it s time to add a few more tests It s important to test not only the new else less if but also the new return statement By navigating though the test grammar py file we can find a test for pretty much every grammar rule The first one I look for is test if else expr This test doesn t fail so it only tests for the happy case To make it more robust we need to add two new tests to check if True and if False case self assertEqual lt if None self assertEqual lt if False I run everything again all tests pass this time ps bool in Python is subclass of integer so you can use to denote True and for FalseRan tests in sOK Tests result SUCCESS test OK Total duration msTests result SUCCESSLastly we need the tests for the return rule They re defined in the test return test Just like the if expression one this test pass with no modification To test this new use case I create a function that receives a bool argument and returns if the argument is true when it s false it skips the return just like the manual tests I have been doing up to this point def g test a return a if test a return a self assertEqual g False self assertEqual g True Now save the file and re run test grammar one more time Ran tests in sOK Tests result SUCCESS test OK Total duration msTests result SUCCESSAll good in the hood test grammar passes with flying colors and the last thing just in case is to re run the full test suite python m test jAfter a while all tests pass and I m very happy with the result LimitationsIf you know Ruby well by this point you ve probably noticed that what I did here is not the same as a conditional modifier For example in Ruby you can run actual expressions in these modifiers irb main gt a irb main gt a if false gt nilirb main gt a gt irb main gt a if true gt I cannot do the same with my implementation gt gt gt a gt gt gt a if FalseTraceback most recent call last File lt stdin gt line in lt module gt TypeError unsupported operand type s for int and NoneType gt gt gt a if True gt gt gt aWhat this reveals is that the return rule I created is just a workaround If I want to make it as close as possible to Ruby s conditional modifier I ll need to make it work with other statements as well not just return Nevertheless this is fine My goal with this experiment was just to learn more about Python internals and see how would I navigate a little known code base written in C and make the appropriate changes to it And I have to admit that I m pretty happy with the results ConclusionAdding a new syntax inspired by Ruby is a really nice exercise to learn more about the internals of Python Of course if I had to convert this as a PR the core developers would probably find a few shortcomings as I have already found and described in the previous section However since I did this just for fun I m very happy with the results The source code with all my changes is on my CPython fork under the branch ruby if new I hope you ve found this post cool and let s see what comes next Other posts you may like Useful Resources To Learn Python s Internals From Scratch See you next time This post was originally published at |
2021-08-21 09:15:00 |
海外ニュース |
Japan Times latest articles |
COVID-19 tracker: Tokyo reports over 5,000 cases for fourth straight day |
https://www.japantimes.co.jp/news/2021/08/21/national/japan-coronavirus-august-21/
|
tokyo |
2021-08-21 18:30:15 |
海外ニュース |
Japan Times latest articles |
As delta rages, Japan starts preparing for COVID-19 booster shots |
https://www.japantimes.co.jp/news/2021/08/21/national/covid-vaccine-boosters-japan/
|
As delta rages Japan starts preparing for COVID booster shotsWhile two shots of the vaccines have been shown to be widely effective in preventing serious illness studies suggest that protection may wane over time |
2021-08-21 18:16:46 |
北海道 |
北海道新聞 |
中6―2神(21日) 中日が先行逃げ切り |
https://www.hokkaido-np.co.jp/article/580597/
|
適時打 |
2021-08-21 18:12:00 |
北海道 |
北海道新聞 |
世界で子どもの感染拡大 日本も増加、学校対策急務 |
https://www.hokkaido-np.co.jp/article/580595/
|
世界各国 |
2021-08-21 18:01:00 |
北海道 |
北海道新聞 |
パラリンピック、コロナ対策が「成功の鍵」 IPC会長、バブル方式に自信 |
https://www.hokkaido-np.co.jp/article/580581/
|
国際パラリンピック委員会 |
2021-08-21 18:05:41 |
北海道 |
北海道新聞 |
インターハイ、青森山田が決勝へ サッカー男子、米子北と対戦 |
https://www.hokkaido-np.co.jp/article/580580/
|
体育大会 |
2021-08-21 18:04:16 |
北海道 |
北海道新聞 |
22日の予告先発 日ハムは上沢 |
https://www.hokkaido-np.co.jp/article/580596/
|
予告先発 |
2021-08-21 18:02:00 |
北海道 |
北海道新聞 |
藤井聡太が三冠か豊島将之タイか 将棋叡王戦22日に第4局 |
https://www.hokkaido-np.co.jp/article/580577/
|
藤井聡太 |
2021-08-21 18:04:06 |
ビジネス |
東洋経済オンライン |
夏の男性ファッション、差がつく作法3選【動画】 人気ファッションスタイリストに聞いてみた | ファッション・トレンド | 東洋経済オンライン |
https://toyokeizai.net/articles/-/449719?utm_source=rss&utm_medium=http&utm_campaign=link_back
|
東洋経済オンライン |
2021-08-21 18:05:00 |
コメント
コメントを投稿