b0nfire.xyz is a Fediverse instance that uses the ActivityPub protocol. In other words, users at this host can communicate with people that use software like Mastodon, Pleroma, Friendica, etc. all around the world.

This server runs the snac software and there is no automatic sign-up process.

Site description
It's lit
Admin email
ww@mailfire.xyz
Admin account
@firekeeper@b0nfire.xyz

Search results for tag #python

[?]🌈 ☯️Teresita🐧👭 » 🌐
@linuxgal@techhub.social

lets one have unicode characters as variables, which is nice.

    [?]David, a Bostonian in Tokyo. » 🌐
    @djl@mastodon.mit.edu

    I'd like to do some "graphics" programming, but a specific type.

    I want to display white dots on a black backround. Calculate a new set of dots, and spit them to the screen. Don't mind if I have to turn off old dots myself.

    SBCL would be optimal, Python OK, C/C++ no thanks city.

    Do any GUI toolkits support such a widget???

    Any recommendations/experience doing this sort of thing???

      [?]🌈 ☯️Teresita🐧👭 » 🌐
      @linuxgal@techhub.social

      Tell to recite the powers of two in English

      $ seq 1 16|while read n;do echo $((2**n));done|python3 -c "import sys,inflect;p=inflect.engine();[print(p.number_to_words(int(x.strip()))) for x in sys.stdin if x.strip()]"

        [?]🌈 ☯️Teresita🐧👭 » 🌐
        @linuxgal@techhub.social

        Check your homework with

        >>> import sympy
        >>> t = sympy.symbols('t')
        >>> y = 1 / sympy.sqrt(t)
        >>> print (sympy.diff(y,t))
        -1/(2*t**(3/2))
        >>>

          [?]🌈 ☯️Teresita🐧👭 » 🌐
          @linuxgal@techhub.social

          Calculate pi to n digits with

          #!/usr/bin/python3
          from decimal import Decimal, getcontext
          import sys
          digits = int(sys.argv[1]) if len(sys.argv) > 1 else 50
          getcontext().prec = digits + 5
          def arctan(x):
          x = Decimal(x)
          x2 = x * x
          term = Decimal(1) / x
          total = term
          n = 1
          sign = -1
          while True:
          term = term / x2
          delta = term / (2 * n + 1)
          if delta == 0:
          break
          total += sign * delta
          sign *= -1
          n += 1
          return total
          pi = 16 * arctan(5) - 4 * arctan(239)
          pi = +pi
          print(f"Pi to {digits} digits:\n{str(pi)[:digits+2]}")

            [?]🌈 ☯️Teresita🐧👭 » 🌐
            @linuxgal@techhub.social

            Build a random maze with

            #!/usr/bin/python3
            from random import shuffle, randrange
            def makemaze(w=20,h=12):
            vis = [[0] * w + [1] for _ in range(h)] + [[1] * (w + 1)]
            ver = [["| "] * w + ['|'] for _ in range(h)] + [[]]
            hor = [["+--"] * w + ['+'] for _ in range(h + 1)]
            def walk(x, y):
            vis[y][x] = 1
            d = [(x - 1, y), (x, y + 1), (x + 1, y), (x, y - 1)]
            shuffle(d)
            for (xx, yy) in d:
            if vis[yy][xx]: continue
            if xx == x: hor[max(y, yy)][x] = "+ "
            if yy == y: ver[y][max(x, xx)] = " "
            walk(xx, yy)
            walk(randrange(w), randrange(h))
            s = ""
            for (a, b) in zip(hor, ver):
            s += ''.join(a + ['\n'] + b + ['\n'])
            return s
            print(makemaze())

              [?]🌈 ☯️Teresita🐧👭 » 🌐
              @linuxgal@techhub.social

              Find the intersection of two lines from four points with under

              #!/usr/bin/env python3
              import sys,numpy as n
              p,q,r,s=map(n.array,((float(sys.argv[i]),float(sys.argv[i+1])) for i in (1,3,5,7)))
              M=n.c_[q-p,s-r]
              d=n.linalg.det(M)
              if abs(d)<1e-10:
              print("Coincident" if abs(n.cross(q-p,r-p))<1e-10 else "Parallel")
              else:
              t,_=n.linalg.solve(M,r-p)
              print(p+t*(q-p))

                [?]🌈 ☯️Teresita🐧👭 » 🌐
                @linuxgal@techhub.social

                Logical truth tables in

                #!/usr/bin/env python3
                import sys
                from itertools import product
                bexp=" ".join(sys.argv[1:])
                code=compile(bexp,"<string>","eval")
                names=code.co_names
                print("\n" + " ".join(names),":",bexp)
                for values in product(range(2), repeat=len(names)):
                env=dict(zip(names,values))
                print(" ".join(map(str,values)),":",int(eval(code,env)))

                  [?]🌈 ☯️Teresita🐧👭 » 🌐
                  @linuxgal@techhub.social

                  #!/usr/bin/env python3
                  from datetime import*
                  t=datetime.today()
                  print("Only",(datetime(t.year,12,25)-t).days,"shopping days until Christmas.")

                    [?]🌈 ☯️Teresita🐧👭 » 🌐
                    @linuxgal@techhub.social

                    Plot a 3D sphere with

                    #!/usr/bin/python3
                    import numpy as np
                    import matplotlib.pyplot as plt
                    theta, phi = np.linspace(0, 2 * np.pi, 50), np.linspace(0, np.pi, 20)
                    THETA, PHI = np.meshgrid(theta, phi)
                    R = 1.0
                    X = R * np.sin(PHI) * np.cos(THETA)
                    Y = R * np.sin(PHI) * np.sin(THETA)
                    Z = R * np.cos(PHI)
                    fig = plt.figure()
                    ax = fig.add_subplot(1,1,1, projection='3d')
                    plot = ax.plot_wireframe(X, Y, Z, rstride=1, cstride=1, linewidth=.1, color='red', antialiased=False, alpha=1)
                    plt.show()

                      [?]🌈 ☯️Teresita🐧👭 » 🌐
                      @linuxgal@techhub.social

                      Convert time in seconds to larger units with :

                      #!/usr/bin/env python3
                      import sys
                      sec=int(sys.argv[1])
                      def dur(sec):
                      t=[]
                      for dm in (60,60,24,7):
                      sec, m=divmod(sec,dm)
                      t.append(m)
                      t.append(sec)
                      return ', '.join('%d %s' % (num,unit)
                      for num, unit in zip(t[::-1], 'wk d hr min sec'.split())
                      if num)
                      print ("%7d seconds = %s" % (sec,dur(sec)))

                        [?]🌈 ☯️Teresita🐧👭 » 🌐
                        @linuxgal@techhub.social

                        Invoke the Dark Lord with using turtle graphics:

                        #!/usr/bin/env python3
                        import turtle
                        turtle.bgcolor("green")
                        t = turtle.Turtle()
                        t.color("red", "blue")
                        t.begin_fill()
                        for _ in range(5):
                        t.forward(200)
                        t.right(144)
                        t.end_fill()
                        t.hideturtle()
                        turtle.exitonclick()

                          [?]🌈 ☯️Teresita🐧👭 » 🌐
                          @linuxgal@techhub.social

                          Calculate the complete elliptic integral of the second kind with (in this case the perimeter of the orbit of Mercury in AU):

                          #! /usr/bin/python3
                          import math
                          import sys
                          a = float(sys.argv[1])
                          b = float(sys.argv[2])
                          h = ((a - b) / (a + b))**2
                          eps = sys.float_info.epsilon
                          def binom_half(n):
                          coef = 1.0
                          for k in range(n):
                          coef *= (0.5 - k) / (k + 1)
                          return coef
                          perimeter = 0.0
                          n = 0
                          term = 1.0
                          while abs(term) > eps:
                          coef = binom_half(n)
                          term = (coef**2) * h**(2*n)
                          perimeter += term
                          n += 1
                          perimeter *= math.pi * (a + b)
                          print(f"Ellipse perimeter: {perimeter:.17f}")
                          print(f"Series converged after {n} terms")

                            [?]🌈 ☯️Teresita🐧👭 » 🌐
                            @linuxgal@techhub.social

                            Factors with

                            #! /usr/bin/python3
                            from sys import*
                            from sympy.ntheory import factorint as f
                            for i in range(int(argv[1]),int(argv[2])+1):print(i,f(i,multiple=1))

                              [?]🌈 ☯️Teresita🐧👭 » 🌐
                              @linuxgal@techhub.social

                              Plot an ellipsoid with

                              #! /usr/bin/env python3
                              import matplotlib.pyplot as plt
                              import numpy as np
                              fig = plt.figure()
                              ax = fig.add_subplot(111, projection='3d')
                              r = 10
                              u = np.linspace(0, 2 * np.pi, 100)
                              v = np.linspace(0, np.pi, 100)
                              x = r * np.outer(np.cos(u), np.sin(v))
                              y = r * np.outer(np.sin(u), np.sin(v))
                              z = r * np.outer(np.ones(np.size(u)), np.cos(v))
                              ax.plot_surface(x, y, z, color='linen', alpha=0.5)
                              theta = np.linspace(0, 2 * np.pi, 100)
                              z = np.zeros(100)
                              x = r * np.sin(theta)
                              y = r * np.cos(theta)
                              ax.plot(x, y, z, color='black', alpha=0.75)
                              ax.plot(z, x, y, color='black', alpha=0.75)
                              zeros = np.zeros(1000)
                              line = np.linspace(-10,10,1000)
                              ax.plot(line, zeros, zeros, color='black', alpha=0.75)
                              ax.plot(zeros, line, zeros, color='black', alpha=0.75)
                              ax.plot(zeros, zeros, line, color='black', alpha=0.75)
                              plt.show()

                                [?]Cheuk Ting Ho » 🌐
                                @cheukting_ho@fosstodon.org

                                I am looking forward to seeing so many of you at , please come to the booth and talk about and maybe ? We have something cool to show you 😉

                                  Al Sweigart boosted

                                  [?]Cheuk Ting Ho » 🌐
                                  @cheukting_ho@fosstodon.org

                                  Check out the scheulde and register ticket here: ep2026.europython.eu/ also make sure you come to the

                                    [?]Leanpub » 🌐
                                    @leanpub@mastodon.social

                                    Python Quick Ref for JS Devs: A Side-by-Side ES6 & TypeScript to Python Reference by Samir Solanki is a new release on Leanpub!

                                    Stop translating Python in your head. Compare ES6/TypeScript and Python side by side and start writing Python with confidence.

                                    Link: leanpub.com/pythonquickref

                                      [?]c't Magazin » 🌐
                                      @ct_Magazin@social.heise.de

                                      heise+ | Die eigenen Lieblingsfilme durch paarweises Vergleichen herausfinden

                                      Gefällt Ihnen Memento oder Heat besser? Unsere kleine Webanwendung findet durch paarweises Vergleichen statistisch Ihre Lieblingsfilme.

                                      heise.de/ratgeber/Die-eigenen-

                                        [?]🌈 ☯️Teresita🐧👭 » 🌐
                                        @linuxgal@techhub.social

                                        Area of any valid triangle with

                                        #!/usr/bin/python3
                                        import sys, math
                                        a, b, c = map(float, sys.argv[1:])
                                        if a + b <= c or a + c <= b or b + c <= a:
                                        print("Error: not a valid triangle")
                                        sys.exit(1)
                                        peri = a + b + c
                                        area = math.sqrt((a + b + c) *
                                        (a + b - c) *
                                        (a - b + c) *
                                        (-a + b + c)) / 4
                                        print("Perimeter =", peri)
                                        print("Area =", area)

                                          [?]🌈 ☯️Teresita🐧👭 » 🌐
                                          @linuxgal@techhub.social

                                          Put text in an ASCII art box with

                                          #!/usr/bin/env python3
                                          import sys
                                          print("+" + "-" * 62 + "+")
                                          for line in sys.stdin:
                                          print(f"| {line.rstrip():<60} |")
                                          print("+" + "-" * 62 + "+")

                                            [?]Medieval Illumination » 🤖 🌐
                                            @medieval_illuminations@mastodon.social

                                            and . Ovide moralisé en prose, Bruges ca. 1470-1480. BnF, Français 137, fol. 8r.

                                            #Apollo and #Python. Ovide moralisé en prose, Bruges ca. 1470-1480. BnF, Français 137, fol. 8r.
#medieval #MedievalArt

                                            Alt...#Apollo and #Python. Ovide moralisé en prose, Bruges ca. 1470-1480. BnF, Français 137, fol. 8r. #medieval #MedievalArt

                                              [?]🌈 ☯️Teresita🐧👭 » 🌐
                                              @linuxgal@techhub.social

                                              Print all primes less than 5000 with

                                              python3 -c 'print([i for i in range(2,5000) if all(i%j for j in range(2,int(i**0.5)+1))])'

                                                [?]🌈 ☯️Teresita🐧👭 » 🌐
                                                @linuxgal@techhub.social

                                                Reformat standard input to any width with

                                                #!/usr/bin/python3
                                                import sys
                                                import textwrap
                                                w=int(sys.argv[1])
                                                for line in sys.stdin:
                                                print(textwrap.fill(line,width=w))

                                                  [?]🌈 ☯️Teresita🐧👭 » 🌐
                                                  @linuxgal@techhub.social

                                                  script to show top 20 commands:

                                                  #!/usr/bin/env python3
                                                  from collections import Counter
                                                  import matplotlib.pyplot as plt
                                                  import os
                                                  history_file = os.path.expanduser("~/.bash_history")
                                                  counter = Counter()
                                                  with open(history_file, "r", errors="ignore") as f:
                                                  for line in f:
                                                  line = line.strip()
                                                  if not line or line.startswith("#"):
                                                  continue
                                                  cmdline = line.split("|", 1)[0].strip()
                                                  parts = cmdline.split()
                                                  if not parts:
                                                  continue
                                                  cmd = parts[1] if parts[0] == "sudo" and len(parts) > 1 else parts[0]
                                                  counter[cmd] += 1
                                                  top = counter.most_common(20)
                                                  commands, counts = zip(*top)
                                                  commands = commands[::-1]
                                                  counts = counts[::-1]
                                                  plt.figure(figsize=(10, 6))
                                                  plt.barh(commands, counts)
                                                  plt.title("Top 20 Bash Commands (frequency)")
                                                  plt.xlabel("Usage count")
                                                  plt.tight_layout()
                                                  plt.show()

                                                    [?]Daniel Lakeland » 🌐
                                                    @dlakelan@mastodon.sdf.org

                                                    I programmed python for a living in the late 1990's, as I got into data analysis I switched to R in the very late 1990's and early 2000's, then in 2019 or so switched almost entirely to Julia. I also have experience in C, C++, Common Lisp and lots of other languages.

                                                    I need to write *modern* python for micropython for my project with my kid. What's like the 3 page zine refresher on modern python I should read?

                                                      [?]Daniel Lakeland » 🌐
                                                      @dlakelan@mastodon.sdf.org

                                                      So i managed to load micropython on to one of my ESP32 devices. I am not clear how I load python code onto the board though. The docs weren't super clear on this. Any hints?

                                                        [?]Thayer 🔜EMFCAMP ☎️6090 » 🌐
                                                        @Thayer@mastodon.social

                                                        ! Senior Engineer, based full stack but leaning to devops/infra. 70/30 would be my ideal split. Fully remote UK only, £63,000 non negotiable sadly, but ~20% pension on top. Closing date: WEDS NOON! So get in touch (thayer@team-prime.com) asap if this might be you.

                                                        Org: healthcare, data, ~30 person team. Zero AI currently in place, but some may be implemented very gently/ethically/thoughtfully over the next year, or not!

                                                        Would esp suit someone who prefers chill vs rocket ship.

                                                          Aprazeth boosted

                                                          [?]Mark Dominus » 🌐
                                                          @mjd@mathstodon.xyz

                                                          I'm looking for work, please boost!

                                                          I'm a senior software engineer with 35 years of experience. I've worked across an unusually wide range of domains: mobile game backends, privacy-preserving data platforms, high-throughput COVID testing infrastructure, email and account systems, e-payment processing, job marketplace systems, and bioinformatics. I pick up new domains quickly and have a track record of doing it repeatedly. I understand how to turn business needs into engineering requirements.

                                                          I've worked remotely since the 1990s and can operate with minimal supervision. I don't need hand-holding to find the right problem to solve. Several of my most valued projects were self-directed: I identified the need, built the thing, and shipped it.

                                                          Some of the technologies I'm familiar with include: Python, Perl, TypeScript/JavaScript, Haskell, Go, C, Java. Postgres, MySQL, SQLite. Flask, SQLAlchemy. AWS (Lambda, S3, RDS, SQS, EC2). Docker, Git. Github and Gitlab.

                                                          I've also repeatedly picked up new languages and stacks as needed: Haskell for differential privacy research, TypeScript for a 24/7 AWS Lambda system, Flask for my most recent employer. I've become productive with new systems over and over, and I can do it quickly.

                                                          I'm also a published author (Higher-Order Perl, Morgan Kaufmann), longtime blogger, and conference speaker with a reputation for making complex ideas clear.

                                                          My résumé is at plover.com/~mjd/cv/Mark%20Jaso

                                                          mjd@pobox.com

                                                          Thanks for your attention!

                                                            [?]J. R. DePriest :verified_trans: :donor: :Moopsy: :EA DATA. SF: [She / Her / Goddess] » 🌐
                                                            @jrdepriest@infosec.exchange

                                                            Since there has been a huge influx of new users, I decided to write a new and actually pin it to my profile.
                                                            I'm pushing 50 years old and I live in a Red State that is trying to make me illegal. I'm a / woman married to a heterosexual cisgender woman who frequently talks about the current hellscape for people like me in my Toots.
                                                            I'm / which is probably why all of these sentences start with "I".
                                                            I've worked in for a little over 20 years. I've had lots of roles in , , and . I taught myself , , , and . I'm decent at . I can read and . I enjoy automating things and turning manual processes into scripts.
                                                            I've been the primary to my wife for 8 years since she developed a chronic condition and went on disability.
                                                            My hobbies including short fiction, journaling my , and playing on my laptop and .
                                                            I prefer over over . Still waiting for Amazon to do something, anything with the Stargate property.
                                                            While we loved the including and , in general we prefer over .
                                                            I'm a fan of / , and , especially the existential dread of or . I tend to sympathize with the nameless terrors. I am not a fan of mindless slashers, unrelenting gore, or torture porn. Over-the-top, egregious gore that crosses into the absurd is fine, though, so I am a Sam Raimi fan, obvs. Also, are underappreciated.
                                                            I'm slowly reconnecting with my roots. I knew some stuff about and had a friend who as a tree a lifetime ago and I'm trying to rekindle that.
                                                            We've got and they are our kids. I also happen to love , but we don't have any of those.






                                                              [?]jonny (nonvenomous) [they/them] » 🌐
                                                              @jonny@neuromatch.social

                                                              aw ye whats up my bozos it's static type checking for array shape and dtype constraints so you no longer have to toil in the mines of infinity incomprehensible (ndarray)->ndarray functions like bunch of clowns face smacking in a field of rakes

                                                              numpydantic.readthedocs.io/en/

                                                              E.g. say you have some analysis function that only accepts grayscale images:

[python code follows. a type for 2D grayscale images and 3D RGB images are declared. then functions that return RGB and grayscale images, and finally a functino that only accepts grayscale image. demonstrates that the function fails a type chck when called with an RGB image]

import numpy as np

from numpydantic import NDArray, Shape

GRAYSCALE = NDArray[Shape["* x, * y"], np.uint8]
RGB = NDArray[Shape["* x, * y, 3 rgb"], np.uint8]


def read_rgb() -> RGB:
    return np.ones((1920, 1080, 3), dtype=np.uint8)


def read_grayscale() -> GRAYSCALE:
    return np.ones((1920, 1080), dtype=np.uint8)


def grayscale_mask(frame: GRAYSCALE) -> GRAYSCALE:
    # Probably something fancier than this...
    mask = np.zeros((frame.shape[0], frame.shape[1]), np.uint8)
    mask[frame > 5] = 1
    return mask


# this works
grayscale_mask(read_grayscale())

# this doesn't
grayscale_mask(read_rgb())

examples/incorrect/rgb_gray_frame.py:28: error: Argument 1 to "grayscale_mask"
has incompatible type
"ndarray[tuple[int, int, Literal[3]], dtype[unsignedinteger[_8Bit]]]"; expected
"ndarray[tuple[int, int], dtype[unsignedinteger[_8Bit]]]"  [arg-type]
    grayscale_mask(read_rgb())
                   ^~~~~~~~~~
Found 1 error in 1 file (checked 1 source file)

                                                              Alt...E.g. say you have some analysis function that only accepts grayscale images: [python code follows. a type for 2D grayscale images and 3D RGB images are declared. then functions that return RGB and grayscale images, and finally a functino that only accepts grayscale image. demonstrates that the function fails a type chck when called with an RGB image] import numpy as np from numpydantic import NDArray, Shape GRAYSCALE = NDArray[Shape["* x, * y"], np.uint8] RGB = NDArray[Shape["* x, * y, 3 rgb"], np.uint8] def read_rgb() -> RGB: return np.ones((1920, 1080, 3), dtype=np.uint8) def read_grayscale() -> GRAYSCALE: return np.ones((1920, 1080), dtype=np.uint8) def grayscale_mask(frame: GRAYSCALE) -> GRAYSCALE: # Probably something fancier than this... mask = np.zeros((frame.shape[0], frame.shape[1]), np.uint8) mask[frame > 5] = 1 return mask # this works grayscale_mask(read_grayscale()) # this doesn't grayscale_mask(read_rgb()) examples/incorrect/rgb_gray_frame.py:28: error: Argument 1 to "grayscale_mask" has incompatible type "ndarray[tuple[int, int, Literal[3]], dtype[unsignedinteger[_8Bit]]]"; expected "ndarray[tuple[int, int], dtype[unsignedinteger[_8Bit]]]" [arg-type] grayscale_mask(read_rgb()) ^~~~~~~~~~ Found 1 error in 1 file (checked 1 source file)

                                                              Shape checking

Scalars

Scalar shapes are checked as expected, where the shapes must match exactly.

[python code follows. a correct example shows an NDArray annotation with a Shape[1, 2, 3] (three dimensions with sizes 1, 2, and 3 respectively) as a return value coming from a np.ones() constructor and assigned to x as passing a type check. an incorrect example shows that the type checker fails both between the numpy constructor and return type and the return type and the assignment]

Correct

def make_array() -> NDArray[Shape[1, 2, 3], np.uint8]:
    return np.ones((1, 2, 3), dtype=np.uint8)


x: NDArray[Shape[1, 2, 3], np.uint8] = make_array()

Incorrect

def make_array() -> NDArray[Shape[2, 3, 4], np.uint8]:
    return np.ones((1, 2, 3), dtype=np.uint8)


x: NDArray[Shape[5, 6, 7], np.uint8] = make_array()

error: Incompatible return value type
(got "ndarray[int, dtype[_8Bit]]", expected
"ndarray[tuple[Literal[2], Literal[3], Literal[4]], dtype[_8Bit]]")
 [return-value]
        return np.ones((1, 2, 3), dtype=np.uint8)
               ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
error: Incompatible types in assignment
(expression has type
"ndarray[tuple[Literal[2], Literal[3], Literal[4]], dtype[8Bit]]",
variable has type
"ndarray[tuple[Literal[5], Literal[6], Literal[7]], dtype[_8Bit]]")
 [assignment]
    x: NDArray[Shape[5, 6, 7], np.uint8] = make_array()
                                           ^~~~~~~~~~~~
Found 2 errors in 1 file (checked 1 source file)

                                                              Alt...Shape checking Scalars Scalar shapes are checked as expected, where the shapes must match exactly. [python code follows. a correct example shows an NDArray annotation with a Shape[1, 2, 3] (three dimensions with sizes 1, 2, and 3 respectively) as a return value coming from a np.ones() constructor and assigned to x as passing a type check. an incorrect example shows that the type checker fails both between the numpy constructor and return type and the return type and the assignment] Correct def make_array() -> NDArray[Shape[1, 2, 3], np.uint8]: return np.ones((1, 2, 3), dtype=np.uint8) x: NDArray[Shape[1, 2, 3], np.uint8] = make_array() Incorrect def make_array() -> NDArray[Shape[2, 3, 4], np.uint8]: return np.ones((1, 2, 3), dtype=np.uint8) x: NDArray[Shape[5, 6, 7], np.uint8] = make_array() error: Incompatible return value type (got "ndarray[int, dtype[_8Bit]]", expected "ndarray[tuple[Literal[2], Literal[3], Literal[4]], dtype[_8Bit]]") [return-value] return np.ones((1, 2, 3), dtype=np.uint8) ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ error: Incompatible types in assignment (expression has type "ndarray[tuple[Literal[2], Literal[3], Literal[4]], dtype[8Bit]]", variable has type "ndarray[tuple[Literal[5], Literal[6], Literal[7]], dtype[_8Bit]]") [assignment] x: NDArray[Shape[5, 6, 7], np.uint8] = make_array() ^~~~~~~~~~~~ Found 2 errors in 1 file (checked 1 source file)

                                                              So, if enabled, return values for non-numpy interfaces can declare how to infer their shapes and dtypes:

[python code follows, demonstrates that numpy and zarr constructors are correctly typed from the sizes and dtypes in their constructors (dask is broken, note at bottom). without the plugin they are just generic arrays and Any types]

from typing import reveal_type

import dask.array as da
import numpy as np
import zarr

x = np.zeros((3, 4, 5), dtype=np.uint8)
y = da.zeros((3, 4, 5), dtype=np.uint8)
z = zarr.zeros((3, 4, 5), another=int, dtype=np.uint8)

reveal_type(x)
reveal_type(y)
reveal_type(z)

Without the plugin
note: Revealed type is "numpy.ndarray[tuple[int, int, int], numpy.dtype[numpy.unsignedinteger[numpy._typing._nbit_base._8Bit]]]"
note: Revealed type is "Any"
note: Revealed type is "Any"

With the plugin

note: Revealed type is "numpy.ndarray[tuple[Literal[3], Literal[4], Literal[5], fallback=int], numpy.dtype[numpy.unsignedinteger[numpy._typing._nbit_base._8Bit]]]"
note: Revealed type is "Any"
note: Revealed type is "numpy.ndarray[tuple[Literal[3], Literal[4], Literal[5], fallback=int], numpy.dtype[numpy.unsignedinteger[numpy._typing._nbit_base._8Bit]]]"

Dask is broken

Note that dask’s constructor inference doesn’t work at the moment. This is due to dask’s array creation routines being positively haunted, an untyped wrapped dynamic construction of a function that creates a class that creates a class.

PRs welcome re: figuring out how to type that.

                                                              Alt...So, if enabled, return values for non-numpy interfaces can declare how to infer their shapes and dtypes: [python code follows, demonstrates that numpy and zarr constructors are correctly typed from the sizes and dtypes in their constructors (dask is broken, note at bottom). without the plugin they are just generic arrays and Any types] from typing import reveal_type import dask.array as da import numpy as np import zarr x = np.zeros((3, 4, 5), dtype=np.uint8) y = da.zeros((3, 4, 5), dtype=np.uint8) z = zarr.zeros((3, 4, 5), another=int, dtype=np.uint8) reveal_type(x) reveal_type(y) reveal_type(z) Without the plugin note: Revealed type is "numpy.ndarray[tuple[int, int, int], numpy.dtype[numpy.unsignedinteger[numpy._typing._nbit_base._8Bit]]]" note: Revealed type is "Any" note: Revealed type is "Any" With the plugin note: Revealed type is "numpy.ndarray[tuple[Literal[3], Literal[4], Literal[5], fallback=int], numpy.dtype[numpy.unsignedinteger[numpy._typing._nbit_base._8Bit]]]" note: Revealed type is "Any" note: Revealed type is "numpy.ndarray[tuple[Literal[3], Literal[4], Literal[5], fallback=int], numpy.dtype[numpy.unsignedinteger[numpy._typing._nbit_base._8Bit]]]" Dask is broken Note that dask’s constructor inference doesn’t work at the moment. This is due to dask’s array creation routines being positively haunted, an untyped wrapped dynamic construction of a function that creates a class that creates a class. PRs welcome re: figuring out how to type that.

                                                                Back to top - More...