July 3rd, 2024

Python with Braces

Bython is a Python preprocessor on GitHub, enabling curly brace usage instead of whitespace for indentation. It ensures compatibility with modules like NumPy and Matplotlib. Installation options include pip or GitHub cloning.

Read original articleLink Icon
Python with Braces

Bython is a Python preprocessor tool available on GitHub that allows writing Python code using curly braces instead of relying on whitespace for indentation. It helps avoid indentation issues and is compatible with Python modules like NumPy and Matplotlib. Bython files with a .by extension are translated into Python files for execution. Installation can be done via pip from PyPI or by cloning the GitHub repository. The repository structure includes directories for the parser, utilities, manual pages, scripts, and test cases. A code example demonstrates the usage of curly braces in Bython. Additionally, a quick intro explains how to run Bython programs and translate Python files to Bython using `py2by`. For more information, visit the Bython GitHub repository.

Related

As you learn Forth, it learns from you (1981)

As you learn Forth, it learns from you (1981)

The Forth programming language is highlighted for its unique features like extensibility, speed, and efficiency. Contrasted with Basic, Forth's threaded code system and data handling methods make it versatile.

What scripting languages come out of the box on Debian 12?

What scripting languages come out of the box on Debian 12?

The article discusses pre-installed scripting languages in Debian 12: bash, Python 3, awk, sed, and Perl. Emphasizes convenience for offline work, ease of script transfer, and benefits of learning Python.

Igneous Linearizer: semi-structured source code

Igneous Linearizer: semi-structured source code

The Igneous Linearizer project enhances source code in Obsidian Markdown format, enabling features like links and transclusion. It sacrifices AST correctness for compatibility with text editors and Git, benefiting literate programming. Users must follow specific input file formats for optimal use.

Show HN: Adding Mistral Codestral and GPT-4o to Jupyter Notebooks

Show HN: Adding Mistral Codestral and GPT-4o to Jupyter Notebooks

Pretzel is an open-source tool enhancing Jupyter with AI code generation, inline tab completion, sidebar chat, and error fixing. Seamless transition from Jupyter is possible, maintaining compatibility. Installation via 'pip install pretzelai'.

Python Modern Practices

Python Modern Practices

Python development best practices involve using tools like mise or pyenv for multiple versions, latest Python version, pipx for app running. Project tips include src layout, pyproject.toml, virtual environments, Black, flake8, pytest, wheel, type hinting, f-strings, datetime, enum, Named Tuples, data classes, breakpoint(), logging, TOML config for efficiency and maintainability.

Link Icon 56 comments
By @12_throw_away - 7 months
I wish there were even more of this sort of thing, even though I'm an anti-braces zealot - it's crazy to me that, here in 2024, code is still so tightly linked to specific textual representations. Maybe there's an alternate reality where IDEs and development tooling got better and better post-smalltalk/lisp, instead of ... whatever we have now. Maybe we'd have editors and viewers where you could configure the syntax however you wanted. And sure, it would be persisted to disk in some canonical representation, maybe text, maybe a DB ... but you'd never need to worry about it, because all your tooling (VCS, diffs, refactoring tools, etc) would work with the AST, and you'd never need to worry about tabs or spaces ever again.
By @necovek - 7 months
This is a great discussion with many a differing point of view.

To some, significant indentation is better.

Others — too used to braces — miss them dearly in Python.

Next ones, vie for the non-text source code, something to get us past these discussions altogether (editors working on .pyc files directly?).

For programs to be maintained, they need to be read, understood and improved. One—often undervalued—skill in programming is to write beautiful code, because that is more art than craft. And unfortunately, tools like Black prohibit the true artists from expressing themselves clearly with code formatting too. And to those, white-space or braces matters on a different level, and everything else is attempting to make up excuses for why one is better than other.

And while conceptual operations we do on the code seem simple on the surface, devising an editing tool that would do semantic operations on the AST is fricking hard and likely to be very non-ergonomic. Look at all the attempts to make code refactoring tooling: it's crazily complex and confusing that it's simpler to just go and grep for a string and fix anything you find.

As long as it's faster to use regular editing operations to shuffle code around, indent or unindent it (or wrap it with braces), tweak one thing here or there, simple text editors will mostly rule the world of programming.

By @darby_nine - 7 months
I don't understand why we don't make the aesthetic aspects of syntax (e.g. block delimitation) to be a feature of the editor rather than the source of truth for the code. For all unix profited from text I think we have the tooling necessary to move our storage and editors beyond it, and it's been obvious the entire time it comes with non-trivial liability converting to and from more reliably structured representations.
By @DonHopkins - 7 months
Python has always fully supported C style braces out of the box: you simply have to put a # before them:

    if foo == 1: # {
        print "one foo"
    # }
It also supports PASCAL style begin/end:

    if foo == 1: # begin
        print "one foo"
    # end
And it's fully internationalized, even supporting mixing multiple languages:

    if foo == 1: # beginnen
        print "one foo"
    # 終了
In fact, you can even mix styles:

    if foo == 1: # begin
        print "one foo"
    # }
Or optionally leave one of them out, or spell them any way you like, if you feel like it:

    if foo == 2:
        print "one foo"
    # fi
Even verbose COBOL style:

    if foo == 1: # perform conditional foo value check
        print("one foo")
    # end perform conditional
By @gary_0 - 7 months
Braces, maybe. But I've always felt that semicolons at the end of lines were just noise. I can tell it's the end of the line because it's the end of the line. The few cases of ambiguity that happen can be solved by common sense (in the programmer or in the parser).
By @pasc1878 - 7 months
For another way of removing indentation needed for structure.

Make python a lisp - indentation is just the number of brackets.

Hy - http://hylang.org

By @p5a0u9l - 7 months
Glad that auto formatting tools like black and ruff (at least in Python world) are increasingly becoming the norm. It’s really nice to not think about whitespace or humor these silly arguments.
By @Ringz - 7 months
“Perfection is achieved, not when there is nothing more to add, but when there is nothing left to take away.”

Antoine de Saint-Exupéry

Unfortunately, we still live in an era where humans have to adapt to technology rather than the other way around. From my perspective, this is particularly true for programming.

For me, Python is a good (though not ideal) mix of simple syntax and power. The language is characterized by low redundancy, meaning it uses fewer unnecessary characters like semicolons or curly braces to mark the end of a line. If a human can recognize the end of a line without special characters, then the compiler should be able to as well.

As someone with ADHD, I find it particularly difficult not to get distracted by these and other superfluous details. These small distractions add up and can become very burdensome. Interestingly, I found it easier to program in Assembler and Modula than in languages like C++ (MSVC), PHP, or JavaScript – at least as long as the projects were small.

Even a brief look at Rust’s syntax causes me almost physical discomfort, no matter how great, powerful, and useful the language may be.

For this reason, I almost exclusively use the terminal for emails, calendar, and programming, even though complex GUIs can simplify some tasks.

Although Python is not perfect in terms of syntax, it offers a good balance. Perhaps one day, before the perfect programming language exists, we will be able to use AI and ML to explain to the computer what a program should do with simple language (better than ChatGPT right now), just like Captain Picard. In fantasy, a few letters, punctuation marks, and some grammar is all that is needed. This may lead to inaccuracies in human-to-human communication, but that does not mean the same problems must occur in communication with an intelligent compiler.

Making syntax as “human-readable” as possible should always be the highest priority. We could unlock so much potential this way.

By @usrbinbash - 7 months
The problem I have with such tools, is interoperability.

This transpiles into Python. Okay. So for this to work in a collaborative environment, EVERYONE working on the code has to use it. Given how popular python is, and the natural inertia of programming languages, I simply don't see that happening.

The reasons for this are legion: From programmers simply being used to how python looks, over IDEs and linters that would have to be remade, all the way to automated tooling.

And even if all that were not a problem: This introduces one more step and one more element into the build chain. Which is something I can't see DevOps doing, for a, at the end of the day, purely cosmetic change.

By @woolion - 7 months
For those interested in the "no syntax" approach (the editor being aware of the structure and able to operate natively on it), there are a number of projects [0] that go beyond simple Proof of Concepts. Naturally there are more on Lisp-y languages since there is much less work to go back and forth between syntax and structure. Then is another interesting related discussion [1] from 2015, "Programmer Tooling Beyond Plain Text". Since discusses article seems down, I've added the archive link at [2].

[0] https://github.com/yairchu/awesome-structure-editors/blob/ma...

[1] https://news.ycombinator.com/item?id=9495493

[2] https://web.archive.org/web/20151023070244/http://joelburget...

By @a3w - 7 months
First of april is not now. So I will seriously discuss the idea:

IMHO, some level of linting should be required. I would often have to reject lengthy and excellent pull requests (PRs), just because autoformat was not pressed and three instead of four whitespaces are in kotlin code. That annoys everyone. Python does that right, code won't compile with the three version whitespace, which is easily spotted before the PR.

By @lofaszvanitt - 7 months
People have these culture wars about braces in the end or new line, while the whole thing should be on the editor's side. It shows you the way you want it, then convert it to the agreed upon style upon saving.

Text editors are easy, but are waaaaay in the past. There could be much much better 3D like editors out there, but everyone is lazy to make one that would make your life much easier.

By @psychoslave - 7 months
On that side, as for many others, Ruby captures my love. You can use `{…}` or `do … end` as you see best fit. And enforcing some indentation convention is always an option with some upper level tools. What makes perfect sense for integration in a large codebase is ridiculous while interacting with a REPL.

Now Ruby as his own defects of course. Static type can be integrated through Sorbet, but that still something out of the core for now. On that side, PHP had during the last years shown a far more remarkable pace in integrating many advanced feature for OOP (and functional stuffs are also progressing well). That said, the foundation of Ruby still win my preference in term of elegance and feeling of coherence.

I didn’t touch that much Python over the last few years. The only (significant) reason I would see it as opportune is its heavy use in ML and the like domains, and I didn’t have an opportunity to dig this domain much.

By @Fraterkes - 7 months
Is significant whitespace good or bad? Maybe 3/7/2024 is finally the day we get to the bottom of this.
By @aitchnyu - 7 months
Might as well allow multiline lambdas and js-style ternary statements. JS (under JSX skin) makes constructing a tree of components really ergonomic. Similar libraries in Python rely on doing side effects and context managers and dsls.

Also TS has slightly more consistent syntax for return types than Python. ``` // TS

function fn(a: Type, b: Type) : Type {

}

// Python def fn(a: Type, b:Type) -> Type {

} ```

But I want python to have to close braces on as few lines as possible. Yes I'm a Black user and wonder how.

By @IshKebab - 7 months
Of all the things to hate about Python, this seems like the least. The indentation definitely looks nicer. I'd say the only real disadvantages it has are a) you are definitely restricted to statement-based constructs; no inline function definitions etc., and b) pasting stuff into the REPL is a mess.

They could fix the latter, but the REPL is Python tooling so it is required to be awful.

By @glimmung - 7 months
I'm glad this exists for those who want it, but for me the added noise / cognitive load of all those braces is painful.
By @calmbonsai - 7 months
With Python, use Black or go home.
By @teddyh - 7 months
The documentation notes that reserving braces for blocks makes it very ugly to deal with dict literals, but it’t also terrible for sets, set comprehensions, and dict comprehensions. You’d think they’d choose some other characters than braces in order to avoid this. I seem to recall that RPL used « and » for program blocks.
By @adolph - 7 months
I had to do a quick check if python do have teeth and thus use braces. My initial thought was that they do not as the most prominent teeth on snakes are fangs and python are not venomous. They do have teeth for holding their pray as they constrict it.

Pythons use their sharp, backward-curving teeth, four rows in the upper jaw, two in the lower, to grasp prey which is then killed by constriction; after an animal has been grasped to restrain it, the python quickly wraps a number of coils around it. Death occurs primarily by cardiac arrest.

https://en.wikipedia.org/wiki/Pythonidae

By @0x1ceb00da - 7 months
Could've been a python parser patch because it adds a preprocessing step. Wouldn't have been that difficult to maintain since the syntax doesn't change that much.
By @pansa2 - 7 months
Does this add support for multiple-statement lambdas?

IMO lack of support for them (because of the lack of a good syntax) is the main downside of Python’s significant indentation.

By @gabrielsroka - 7 months
I found this here years ago: Python With Kurly braces.

https://github.com/umlet/pwk

By @bloopernova - 7 months
I've recently created a couple of Lambdas using nodejs rather than my normal Python.

Despite node feeling more verbose, I've found that I understand node easier than Python. It's definitely strange to me, because there can't be that much difference between the 2, but parentheses seem to make it easier to follow structure?

By @thih9 - 7 months
> You should still write beautiful code, but if you mess up with tabs/spaces, or copy one piece of code to another that uses a different indentation style, it won't break.

This seems contradictory. But I see the benefits. Perhaps braces and an official linter would be a more ergonomic approach.

By @lionkor - 7 months
All significant characters should be non-empty/visible, I think that sums up why I prefer braces.
By @JodieBenitez - 7 months
I had to check the calendar. Twice.
By @wiml - 7 months
Didn't Python used to support braces as an alternative to indentation? I remember it being a feature back in the 1.x days, but I can't find it in the old language docs, so I must be thinking of some other language.
By @ivanche - 7 months
As they say, python looks exactly like Guido indented it to look.
By @dmurray - 7 months
> At the moment, Bython is written in Python.

PR #1: Makes Bython self-hosting

By @hoosieree - 7 months
mascot: a python, with braces
By @sambalbadjak - 7 months
I did not know I had such a strong reaction to seeing curly braces in python. brr not my cup of tea. but all the power to you
By @sgt101 - 7 months
I don't like whitespace compulsion but I can live with it.

self.onandonandon is a real pain along with copy.deepcopy

By @samatman - 7 months
I was wondering if this was sincere or a troll, until I saw the semicolons.

Troll. 100%. A good one at that.

By @jackblemming - 7 months
Can we get python with sane async, parallelism, map/reduce and scoping instead?
By @pyuser583 - 7 months
Python supports extensions. Maybe a better way than translating text files?
By @RyEgswuCsn - 7 months
People spent considerable amount of effort developing systems that separate contents from styles (latex, html/css, etc). And with Python people think it’s a good idea to encode contents as styles…
By @autoexec - 7 months
Honestly, the weird whitespace annoyance doesn't bother me half as much as needing parentheses for print.
By @shantnutiwari - 7 months
The library is 6 years old, and I remember we all laughed when it came out. Why is it on the 1st page now?
By @math_dandy - 7 months
Should write a PEG grammar.
By @mort96 - 7 months
Honestly, this looks more readable than Python. Noticing whether something is 3 or 4 levels less indented than something else is really really hard. Noticing whether there are 3 or 4 braces is easy.
By @cynicalsecurity - 7 months
The same goes for Golang. The reverse position of a variable name and type in function arguments is absolutely infuriating. I hate the person who did it, it's absolutely stupid.
By @newaccountman2 - 7 months
I think Python is terrible, but whitespace is ok. lol
By @teddyh - 7 months

  >>> from __future__ import braces
  File "<stdin>", line 1
  SyntaxError: not a chance
  >>>
By @surfingdino - 7 months
Sacrilege /s
By @AcerbicZero - 7 months
Whitespace is def wrong, but I'm not sure this actually makes things much better....still pretty awesome idea!
By @kaplpot - 7 months
This is the least of Python's problems, but makes for a good populist discussion that will keep Python on the front page for yet another 10 hours.

This is how Python got big: Discuss cute issues endlessly, pretend to be a funny, benevolent community. But real issues like performance, correctness or security are never addressed, and people who dare to mention them are punished severely.