953 Matching Annotations
  1. Oct 2021
    1. >>> page = Page.objects.get(title="A Blog post") >>> page <Page: A Blog post> # Note: the blog post is an instance of Page so we cannot access body, date or feed_image >>> page.specific <BlogPage: A Blog post>

      You can convert a Page object to its more specific user-defined equivalent using the .specific property. This may cause an additional database lookup.

    1. Use settings to change the default templates used for each tag Specify templates using template and sub_menu_template arguments for any of the included menu tags (See Specifying menu templates using template tag parameters). Put your templates in a preferred location within your project and wagtailmenus will pick them up automatically (See Using preferred paths and names for your templates).

      Dónde especificar las plantillas para los menús. Si no usas las tuyas, el paquete usa plantillas por defecto usando bootstrap3

    2. While main menus always have to be defined for each site, for flat menus, you can support multiple sites using any of the following approaches: Define a new menu for each site Define a menu for your default site and reuse it for the others Create new menus for some sites, but use the default site’s menu for others You can even use different approaches for different flat menus in the same project. If you’d like to learn more, take a look at the fall_back_to_default_site_menus option in Supported arguments

      Usar main menu o flat menu en wagtail

    3. Have you noticed how the aricle pages are not shown below the ‘Latest news’ item, despite specifying allow_subnav=True on the menu item? Only pages with a show_in_menus value of True will be displayed (at any level) in rendered menus. The field is added by Wagtail, so is present for all custom page types. For page types that are better suited to showing on listing/index pages (for example: news articles or events) - you can set the show_in_menus_default attribute on the page type class to False to exclude them from menus by default.

      Configuraciones básicas de wagtailmenus para que se muestren o no

    1. Now since the “compiling to bytecode” step above takes a noticeable amount of time when you import a module, Python stores (marshalls) the bytecode into a .pyc file, and stores it in a folder called __pycache__. The __cached__ parameter of the imported module then points to this .pyc file.When the same module is imported again at a later time, Python checks if a .pyc version of the module exists, and then directly imports the already-compiled version instead, saving a bunch of time and computation.

      Python takes benefit of caching imports

    2. Bytecode is a set of micro-instructions for Python’s virtual machine. This “virtual machine” is where Python’s interpreter logic resides. It essentially emulates a very simple stack-based computer on your machine, in order to execute the Python code written by you.

      What bytecode does

    3. Python always runs in debug mode by default.The other mode that Python can run in, is “optimized mode”. To run python in “optimized mode”, you can invoke it by passing the -O flag. And all it does, is prevents assert statements from doing anything (at least so far), which in all honesty, isn’t really useful at all.

      Python debug vs optimized mode

    4. let’s say you only want to support integer addition with this class, and not floats. This is where you’d use NotImplemented

      Example use case of NotImplemented:

      class MyNumber:
          def __add__(self, other):
              if isinstance(other, float):
                  return NotImplemented
      
              return other + 42
      
    5. Now I should mention that all objects in Python can add support for all Python operators, such as +, -, +=, etc., by defining special methods inside their class, such as __add__ for +, __iadd__ for +=, and so on.

      For example:

      class MyNumber:
          def __add__(self, other):
              return other + 42
      

      and then:

      >>> num = MyNumber()
      >>> num + 3
      45
      
    6. NotImplemented is used inside a class’ operator definitions, when you want to tell Python that a certain operator isn’t defined for this class.

      NotImplemented constant in Python

    7. every exception is a subclass of BaseException, and nearly all of them are subclasses of Exception, other than a few that aren’t supposed to be normally caught.

      on Python's exceptions

    8. builtin scope in Python:It’s the scope where essentially all of Python’s top level functions are defined, such as len, range and print.When a variable is not found in the local, enclosing or global scope, Python looks for it in the builtins.

      builtin scope (part of LEGB rule)

    9. you can use the nonlocal keyword in Python to tell the interpreter that you don’t mean to define a new variable in the local scope, but you want to modify the one in the enclosing scope.

      nonlocal

    1. in Python 3.0 (alongside 2.6), A new method was added to the str data type: str.format. Not only was it more obvious in what it was doing, it added a bunch of new features, like dynamic data types, center alignment, index-based formatting, and specifying padding characters.

      History of str.format in Python

    1. Finding how to check if a list is empty in Python is not so a tricky task as you think. There are few effective methods available to make your functionalities easy. And of course, list play a paramount role in python that come up with few tempting characteristics listed in the below for your reference.

      Hope so, you got the points that are listed in the above points. All the methods are very simple to write and execute! Probably, the best solution is revealed for your query of “how to Check if a List Is Empty in Python

  2. Sep 2021
    1. One thing to note is that match and case are not real keywords but “soft keywords”, meaning they only operate as keywords in a match ... case block.

      match and case are soft keywords

    2. Use variable names that are set if a case matches Match sequences using list or tuple syntax (like Python’s existing iterable unpacking feature) Match mappings using dict syntax Use * to match the rest of a list Use ** to match other keys in a dict Match objects and their attributes using class syntax Include “or” patterns with | Capture sub-patterns with as Include an if “guard” clause

      pattern matching in Python 3.10 is like a switch statement + all these features

    3. It’s tempting to think of pattern matching as a switch statement on steroids. However, as the rationale PEP points out, it’s better thought of as a “generalized concept of iterable unpacking”.

      High-level description of pattern matching coming in Python 3.10

    1. The best practice is this: #!/usr/bin/env bash #!/usr/bin/env sh #!/usr/bin/env python

      The best shebang convention: #!/usr/bin/env bash.

      However, at the same time it might a security risk if the $PATH to bash points to some malware. Maybe then it's better to point directly to it with #!/bin/bash

    1. As python supports virtual environments, using /usr/bin/env python will make sure that your scripts runs inside the virtual environment, if you are inside one. Whereas, /usr/bin/python will run outside the virtual environment.

      Important difference between /usr/bin/env python and /usr/bin/python

  3. Aug 2021
    1. Here is a list of some open data available online. You can find a more complete list and details of the open data available online in Appendix B.

      DataHub (http://datahub.io/dataset)

      World Health Organization (http://www.who.int/research/en/)

      Data.gov (http://data.gov)

      European Union Open Data Portal (http://open-data.europa.eu/en/data/)

      Amazon Web Service public datasets (http://aws.amazon.com/datasets)

      Facebook Graph (http://developers.facebook.com/docs/graph-api)

      Healthdata.gov (http://www.healthdata.gov)

      Google Trends (http://www.google.com/trends/explore)

      Google Finance (https://www.google.com/finance)

      Google Books Ngrams (http://storage.googleapis.com/books/ngrams/books/datasetsv2.html)

      Machine Learning Repository (http://archive.ics.uci.edu/ml/)

      As an idea of open data sources available online, you can look at the LOD cloud diagram (http://lod-cloud.net ), which displays the connections of the data link among several open data sources currently available on the network (see Figure 1-3).

  4. Jul 2021
    1. The main selling point for Anaconda back then was that it provided pre-compiled binaries. This was especially useful for data-science related packages which depend on libatlas, -lapack, -openblas, etc. and need to be compiled for the target system.

      Reason why Anaconda got so popular

    2. Many of Python’s standard tools allow already for configuration in pyproject.toml so it seems this file will slowly replace the setup.cfg and probably setup.py and requirements.txt as well. But we’re not there yet.

      Potential future of pyproject.toml

    1. Any import statement compiles to a series of bytecode instructions, one of which, called IMPORT_NAME, imports the module by calling the built-in __import__() function.

      All the Python import statements come down to the __import__() function

    1. The fact that FastAPI does not come with a development server is both a positive and a negative in my opinion. On the one hand, it does take a bit more to serve up the app in development mode. On the other, this helps to conceptually separate the web framework from the web server, which is often a source of confusion for beginners when one moves from development to production with a web framework that does have a built-in development server (like Django or Flask).

      FastAPI does not include a web server like Flask. Therefore, it requires Uvicorn.

      Not having a web server has pros and cons listed here

    2. FastAPI makes it easy to deliver routes asynchronously. As long as you don't have any blocking I/O calls in the handler, you can simply declare the handler as asynchronous by adding the async keyword like so:

      FastAPI makes it effortless to convert synchronous handlers to asynchronous ones

    1. Fixtures are created when first requested by a test, and are destroyed based on their scope: function: the default scope, the fixture is destroyed at the end of the test.

      Fixtures can be executed in 5 different scopes, where function is the default one:

      • function
      • class
      • module
      • package
      • session
    2. When pytest goes to run a test, it looks at the parameters in that test function’s signature, and then searches for fixtures that have the same names as those parameters. Once pytest finds them, it runs those fixtures, captures what they returned (if anything), and passes those objects into the test function as arguments.

      What happens when we include fixtures in our testing code

    3. “Fixtures”, in the literal sense, are each of the arrange steps and data. They’re everything that test needs to do its thing.

      To remind, the tests consist of 4 steps:

      1. Arrange
      2. Act
      3. Assert
      4. Cleanup

      (pytest) fixtures are generally the arrange (set up) operations that need to be performed before the act (running the tests. However, fixtures can also perform the act step.

    1. Here is how you can create a fully configured new project in a just a couple of minutes (assuming you have pyenv and poetry installed already).

      Fast track setup of a new Python project

    2. After reading through PEP8, you may wonder if there is a way to automatically check and enforce these guidelines? Flake8 does exactly this, and a bit more. It works out of the box, and can be configured in case you want to change some specific settings.

      Flake8 does PEP8 and a bit more

    3. Pylint is a very strict and nit-picky linter. Google uses it for their Python projects internally according to their guidelines. Because of it’s nature, you’ll probably spend a lot of time fighting or configuring it. Which is maybe not bad, by the way. Outcome of such strictness can be a safer code, however, as a consequence - longer development time.

      Pylint is a very strict linter embraced by Google

    4. The goal of this tutorial is to describe Python development ecosystem.

      tl;dr:

      INSTALLATION:

      1. Install Python through pyenv (don't use python.org)
      2. Install dependencies with Poetry (miniconda3 is also fine for some cases)

      TESTING:

      1. Write tests with pytest (default testing framework for Poetry)
      2. Check test coverage with pytest-cov plugin
      3. Use pre-commit for automatic checks before git commiting (for example, for automatic code refactoring)

      REFACTORING:

      1. Lint your code with flake8 to easily find bugs (it is not as strict as pylint)
      2. Format your code with Black so that it looks the same in every project (is consistent)
      3. Sort imports with isort (so that they are nicely organised: standard library, third party, local)
    5. For Windows, there is pyenv for Windows - https://github.com/pyenv-win/pyenv-win. But you’d probably better off with Windows Subsystem for Linux (WSL), then installing it the Linux way.

      You can install pyenv for Windows, but maybe it's better to go the WSL way

    1. There are often multiple versions of python interpreters and pip versions present. Using python -m pip install <library-name> instead of pip install <library-name> will ensure that the library gets installed into the default python interpreter.

      Potential solution for the Python's ImportError after a successful pip installation

    1. In addition to SQLAlchemy core queries, you can also perform raw SQL queries

      Instead of SQLAlchemy core query:

      query = notes.insert()
      values = [
          {"text": "example2", "completed": False},
          {"text": "example3", "completed": True},
      ]
      await database.execute_many(query=query, values=values)
      

      One can write a raw SQL query:

      query = "INSERT INTO notes(text, completed) VALUES (:text, :completed)"
      values = [
          {"text": "example2", "completed": False},
          {"text": "example3", "completed": True},
      ]
      await database.execute_many(query=query, values=values)
      

      =================================

      The same goes with fetching in SQLAlchemy:

      query = notes.select()
      rows = await database.fetch_all(query=query)
      

      And doing the same with raw SQL:

      query = "SELECT * FROM notes WHERE completed = :completed"
      rows = await database.fetch_all(query=query, values={"completed": True})
      
    1. Uber and Booking.com’s ecosystem was originally JVM-based but they expanded to support Python models/scripts. Spotify made heavy use of Scala in the first iteration of their platform until they received feedback like:some ML engineers would never consider adding Scala to their Python-based workflow.

      Python might be even more popular due to MLOps

  5. Jun 2021
    1. if a module's name has no dots, it is not considered to be part of a package. It doesn't matter where the file actually is on disk.

      what if Python module's name has no dots

    2. if you imported moduleX (note: imported, not directly executed), its name would be package.subpackage1.moduleX. If you imported moduleA, its name would be package.moduleA. However, if you directly run moduleX from the command line, its name will instead be __main__, and if you directly run moduleA from the command line, its name will be __main__. When a module is run as the top-level script, it loses its normal name and its name is instead __main__.

      When Python's module name is __main__ vs when it's a full name (preceded by the names of any packages/subpackages of which it is a part, separated by dots)

    3. A file is loaded as the top-level script if you execute it directly, for instance by typing python myfile.py on the command line. It is loaded as a module if you do python -m myfile, or if it is loaded when an import statement is encountered inside some other file.

      3 cases when a Python file is called as a top-level script vs module

  6. May 2021
    1. The majority of Python packaging tools also act as virtualenv managers to gain the ability to isolate project environments. But things get tricky when it comes to nested venvs: One installs the virtualenv manager using a venv encapsulated Python, and create more venvs using the tool which is based on an encapsulated Python. One day a minor release of Python is released and one has to check all those venvs and upgrade them if required. PEP 582, on the other hand, introduces a way to decouple the Python interpreter from project environments. It is a relative new proposal and there are not many tools supporting it (one that does is pyflow), but it is written with Rust and thus can't get much help from the big Python community. For the same reason it can't act as a PEP 517 backend.

      The reason why PDM - Python Development Master may replace poetry or pipenv

    1. However, the place where pip places that package might not be in your $PATH (thus requiring you to manually update your $PATH afterwards), and on windows the pip install might not take care of python-specific issues for you (see "Notes for Windows Users", above). As such, installation via package managers is recommended instead.
    1. Cookiecutter takes a source directory tree and copies it into your new project. It replaces all the names that it finds surrounded by templating tags {{ and }} with names that it finds in the file cookiecutter.json. That’s basically it. [1]

      The main idea behind cookiecutter

  7. Apr 2021
    1. Holy xxx, it takes 3.37s to calculate merely 1,000,000 reciprocal numbers. The same logic in C takes just a blink: 9ms; C# takes 19ms; Nodejs takes 26ms; Java takes 5ms! and Python takes self-doubting 3.37 SECONDS.

      But numpy takes just 2ms!

  8. Mar 2021
    1. I don't like notebooks.- Joel Grus (Allen Institute for Artificial Intelligence)

      Because it teaches scientists bad programming habits:

      • no modularity (but result depend on order of evaluation)
      • no testabilty
      • cannot view code without opening jupyter
      • missing history (ok %history works) untitled24.ipynb
    1. session.query(Book.author, Chapter.title).select_from(Book).join(Book.chapters) or session.query(Book).options(load_only("author"), joinedload("chapters").load_only("title"))

      Very useful quick guide for how to only load certain foreign key fields.

  9. en.wikipedia.org en.wikipedia.org
  10. Feb 2021
  11. Jan 2021
    1. We recommend the Alpine image as it is tightly controlled and small in size (currently under 5 MB), while still being a full Linux distribution. This is fine advice for Go, but bad advice for Python, leading to slower builds, larger images, and obscure bugs.

      Alipne Linux isn't the most convenient OS for Python, but fine for Go

    1. Did you know that everything you can do in VBA can also be done in Python? The Excel Object Model is what you use when writing VBA, but the same API is available in Python as well.See Python as a VBA Replacement from the PyXLL documentation for details of how this is possible.

      We can replace VBA with Python

    2. Use the magic function “%xl_get” to get the current Excel selection in Python. Have a table of data in Excel? Select the top left corner (or the whole range) and type “%xl_get” in your Jupyter notebook and voila! the Excel table is now a pandas DataFrame.

      %xl_get lets us get the current Excel selection in Python

  12. Dec 2020
  13. Nov 2020
    1. The behaviour of the argument function is extended by the decorator without actually modifying it.

      需要修饰的函数被装饰器(decorator)扩展,且不用修改原函数.

  14. Oct 2020
    1. 和 Python 里的字符串和列表切片不同,你不能在 start, stop 或者 step 这些参数中使用负数。:

      通过 itertools.islice() 可以实现 set dict 的切片操作。

    1. key 形参用来指定在进行比较前要在每个列表元素上调用的函数

      与 C++ 不同,key 形参用来指定进行比较前在每个列表元素上调用的函数。

    1. Przy tych danych wygląda, że właściwie nie ma większej różnicy (nie bijemy się tutaj o 0.01 punktu procentowego poprawy accuracy modelu). Może więc czas treningu jest istotny? Python sns.boxplot(data=models_df, x='time_elapsed', y='model') 1 sns.boxplot(data=models_df, x='time_elapsed', y='model')

      Training time of some popular ML models. After considering the performance, it's worth using XGBoost and LightGBM.

    1. hyperscript is more concise because it's just a function call and doesn't require a closing tag. Using it will greatly simplify your tooling chain.

      I suppose this is also an argument that Python tries to make? That other languages have this con:

      • cons: closing tags make it more verbose / increase duplication and that Python is simpler / more concise because it uses indentation instead of closing delimiters like end or } ?
    1. it is not quite correct to say an object must be immutable to be used as a dictionary key.

      一个对象必须是不可变的才能用作 dict 的键。

      这句话不是很准确。 严谨的说,一个对象必须是可哈希(hashable) 的,才可以用作 dict 的键。

    2. Python does guarantee that the order of items in a dictionary is preserved.

      尽管 Python 中访问字典元素与顺序无关, 但是 Python 会保存字典中元素定义的顺序(Python 3.7 引入的新特性).

    3. they have nothing to do with the order of the items in the dictionary.

      Python 中字典同样可以通过数字来访问,但是与列表不同的是,数字大小与元素的顺序没有关系.

    4. Dictionaries and lists share the following characteristics:

      Python 中字典和列表的相同点是:

      1. 可以修改的
      2. 动态变化,支持增加和缩减.
      3. 支持嵌套. 列表中可以嵌套另一个列表, 字典可以包含另一个字典.字典也可以包含列表.
    1. 这篇文章主要介绍了 Python 中字典处理缺省键值的方法。

      引入了一个新的数据类型 defaultdict,并介绍了它访问和修改不存在键值时的机制。

      主要是重写了 .missing__() 使得在通过 subscription operation 访问修改缺省键值时自动调用该方法,从而避免了dict 的 TypeError。

    2. Using the Python defaultdict Type for Handling Missing Keys

      用 Python 的 defaultdict 处理不存在的键

      想要学习 defaultdict 的原因: 看到 up 主在实现 DFS 的时候用到了这个语法 code

      可以看到的是作者用到了对缺省键的访问操作。

    3. the dictionary assigns it the default value that results from calling list().

      当我们访问不存在键的时候,defaultdict 会自动将调用 default_factory 的值赋给该键。

    4. if you call .setdefault() on an existing key, then the call won’t have any effect on the dictionary.

      如果对已存在的键调用 setdefault ,不会修改原值。

      如果是缺省键,就会创建新的键值对。

    5. if you try to access or modify a missing key, then defaultdict will automatically create the key and generate a default value for it.

      如果你想要访问或者修改一个缺省键值, defaultdict 会自动创建这个键然后生成一个默认值

    1. use code to parameterize calls:

      You can write Python code to parametrize calls:

      python -c "
      from mymodule import set_dragon_feeding_schedule, Creatures, Date
      set_dragon_feeding_schedule(
          feeding_times=['10:00', '14:00', '18:00'],
          dishes={Creatures.Tiger: 2, Creatures.Human: 1},
          start_day=Date('1020-03-01'),
      )
      "
      

      instead of:

      python -m mymodule \
          set_dragon_feeding_schedule \
          --feeding-times ['10:00','14:00','18:00'] # hopefully this way it gets recognized \
          # how will you define parsing a dict with enum to integer mapping? 
          --dishes=Creatures.Tiger:2 \
          --dishes=Creatures.Human:1 \
          --start-day=1020-03-21 # BTW bash allows no comments in multiline calls
      
    2. That’s it. Types are parsed, checked and converted. Defaults and description are picked from function itself. Even provides bash completions you can install. You wrote no code for that!

      Good example of writing CLI interfaces in Python with typer:

      import typer
      from pathlib import Path
      
      app = typer.Typer()
      
      @app.command()
      def find_dragon(name: str, path: Path, min_age_years: int = 200):
          <implementation goes here>
      
      @app.command()
      def feed_dragon(dragon_name: str, n_humans: int = 3):
          <implementation goes here>
      
      if __name__ == "__main__":
          app()
      

      later we can call it that way:

      python example.py find_dragon 'Drake' --path /on/my/planet
      
    1. Merge (|) and update (|=) operators have been added to the built-in dict class. Those complement the existing dict.update and {**d1, **d2} methods of merging dictionaries.

      From Python 3.9 it's much more convenient to:

      • merge dictionaries with the | (pipe) operator, e.g. x | y
      • update them with |=
  15. Sep 2020
    1. The Census FTP page contains the microdata and dictionaries identifying each variable name, location, value range, and whether it applies to a restricted sample. To follow this example, download the April 2017 compressed data file that matches your operating system and unpack it in the same location as the python code. Next download the January 2017 data dictionary text file and save it in the same location.

      This is important

    1. This command will give you the top 25 stocks that had the highest anomaly score in the last 14 bars of 60 minute candles.

      Supriver - find high moving stocks before they move using anomaly detection and machine learning. Surpriver uses machine learning to look at volume + price action and infer unusual patterns which can result in big moves in stocks

    1. Like a string, a list is a sequence of values. In a string, the values are characters; in a list, they can be any type. The values in a list are called elements or sometimes itemsThe syntax for accessing the elements of a list is the same as for accessing the characters of a string—the bracket operator. The expression inside the brackets specifies the index. Remember that the indices start at 0:

             cheeses[0]
      

      ' Cheddar ' Unlike strings, lists are mutable. When the bracket operator appears on the left side of an assignment, it identifies the element of the list that will be assigned. numbers = [42, 123] numbers[1] = 5 numbers [42, 5] The most common way to traverse the elements of a list is with a for loop. The syntax is the same as for strings: for cheese in cheeses: print(cheese) This works well if you only need to read the elements of the list. But if you want to write or update the elements, you need the indices. A common way to do that is to combine the built-in functions range and len : for i in range(len(numbers)): numbers[i] = numbers[i] 2 This loop traverses the list and updates each element. len returns the number of elements in the list. range returns a list of indices from 0 to

      n

      1, where n is the length of the list. Each time through the loop i gets the index of the next element. The assignment statement in the body uses i to read the old value of the element and to assign the new value. The + operator concatenates lists: a = [1, 2, 3] b = [4, 5, 6] c = a + b c [1, 2, 3, 4, 5, 6] The operator repeats a list a given number of times: [0] 4 [0, 0, 0, 0] [1, 2, 3] 3 [1, 2, 3, 1, 2, 3, 1, 2, 3] The first example repeats [0] four times. The second example repeats the list [1, 2, 3] three times. *ython provides methods that operate on lists. For example, append adds a new element to the end of a list: t = [ ' a ' , ' b ' , ' c ' ] t.append( ' d ' ) t [ ' a ' , ' b ' , ' c ' , ' d ' ] extend takes a list as an argument and appends all of the elements: t1 = [ ' a ' , ' b ' , ' c ' ] t2 = [ ' d ' , ' e ' ] t1.extend(t2) t1 [ ' a ' , ' b ' , ' c ' , ' d ' , ' e ' ] This example leaves t2 unmodified. sort arranges the elements of the list from low to high: t = [ ' d ' , ' c ' , ' e ' , ' b ' , ' a ' ] t.sort() t [ ' a ' , ' b ' , ' c ' , ' d ' , ' e ' ] Most list methods are void; they modify the list and return None . If you accidentally write t = t.sort() , you will be disappointed with the result.

    2. *A string is a sequence , which means it is an ordered collection of other values.

      • You can access the characters one at a time with the bracket operator:
               fruit            =
        

        ' banana ' letter = fruit[1] The second statement selects character number 1 from fruit and assigns it to letter . The expression in brackets is called an index .A lot of computations involve processing a string one character at a time. Often they start at the beginning, select each character in turn, do something to it, and continue until the end. This pattern of processing is called a traversal A segment of a string is called a slice . Selecting a slice is similar to selecting a character: s = ' Monty Python ' s[0:5] ' Monty ' s[6:12] ' PythonIt is tempting to use the [] operator on the left side of an assignment, with the intention of changing a character in a string. For example: greeting = ' Hello, world! ' greeting[0] = ' J ' TypeError: ' str ' object does not support item assignment The “object” in this case is the string and the “item” is the character you tried to assign. For now, an object is the same thing as a value, but we will refine that definition later (Section 10.10). The reason for the error is that strings are immutable ,

  16. Aug 2020
    1. barChart = pygal.Bar(height=400)[barChart.add(x[0], x[1]) for x in mean_per_state.items()]display(HTML(base_html.format(rendered_chart=barChart.render(is_unicode=True))))

      How to display html finally in jupyter notebooks

    2. from IPython.display import display, HTMLbase_html = """<!DOCTYPE html><html> <head> <script type="text/javascript" src="http://kozea.github.com/pygal.js/javascripts/svg.jquery.js"></script> <script type="text/javascript" src="https://kozea.github.io/pygal.js/2.0.x/pygal-tooltips.min.js""></script> </head> <body> <figure> {rendered_chart} </figure> </body></html>"""

      How to display html in jupyter notebooks

    1. def main(name: str = typer.Argument(..., help="The name of the user to greet")): typer.echo(f"Hello {name}")

      Add a help text for a CLI argument You can use the help parameter to add a help text for a CLI argument. This example without default

    1. import random import typer def get_name(): return random.choice(["Deadpool", "Rick", "Morty", "Hiro"]) def main(name: str = typer.Argument(get_name)): typer.echo(f"Hello {name}") if __name__ == "__main__": typer.run(main)

      Setting a dynamic default value. And we can even make the default value be dynamically generated by passing a function as the first function argument:

  17. Jul 2020