Better HN
topnewbestaskshowjobs
Log inSign up

BiteCode_dev

24,628 karma · joined Oct 21, 2019 (7y ago) · 5,512 submissions

I write to save you time and effort when dealing with Python:

https://www.bitecode.dev/

Email: contact at bitecode.dev

Submissions

comment 6y ago · link · parent

Unfortunately, you need to:

- discover it

- install it properly

- run it properly

- make it create a venv with the proper python version

- potentially import data from existing setup.py/cfg

- make sure you are always in the right dir when you use it

- not be on windows (poetry shell doesn't work there)

- IDE integration is not great

- people have to chose between this, pip, pip-tools, flit, pipenv, dephell, conda...

And you cannot use it if you are not "in a project". But not all venv are project related.

comment 6y ago · link · parent

> There is no greater hell than talking them through installing a working Python environment. It’s impossible.

I give a lot of Python professional trainings, and I get to do that regularly, in very diverse situations. It's indeed full of gotchas.

Since it's not going to be solved quickly, meanwhile, here is what works if you need to help people setuping python:

1 - Install Python correctly

The first version Python download link for windows is 32 bits. You want 64 bits, so you should actually not click on that. Also, make sure they use the latest minor release possible, as early ones can have weird bugs. Tell people to install from the app store if they are on windows 10, or give them a link to the proper (non web) installer.

Linux: python versions may not be available for their linux distro. Use EPEL for Centos or deadsnake for Ubunto. Other Linux users chose something exotic and must be able to deal with it.

Mac: brew is fine. Official installer too.

Cause: Python support is crazy good. It support 32 bits. 3.4 supports Windows XP. 2.7 supported Atari and Solaris! So there are a lot of installers, and a lot of versions. But also because the official Python website does a poor job at directing the user.

2 - Run Python correctly

This is the great lie of Python running. You cannot just use the "python" command, which is what every doc and tutorials tell you to do.

On linux and mac, tell them to use the suffixed PythonX.Y command, with X.Y being the version of python they need. E.G: python3.6.

On windows, tell them to use the "py -X.Y" command. E.G: py -3.6

Tell them anytime they see a tutorial with "python" in it, they should replace it mentally with "PythonX.Y" or "py -X.Y" depending of who you have in front of you.

Cause: people often ends up with have several versions of Python installed on the same machine, so you can't tell them to just use the "python" command. Of course, windows and unix never agreed an on naming convention. What's more, the Windows situation can lead to a PATH problem, and "python" may not be found, while "py" will always be. We are talking about providing the "py" command everywhere.

3 - Install tools correctly

Introduce them to pip. Tell them to never, ever install stuff using admin rights with it, even if told to by documentation or tutorials. No "sudo". No "run console as admin".

If you need to install a tool, such as black, mypy, pylint, etc., outside of a venv, use "--user" to install it for the current user. This requires no admin rights.

Also, don't use the pip command directly. Use "-m" so that you always know from which python you are installing the command for. E.G:

    python3.6 -m pip install black --user # unix
    py -3.6 -m pip install black --user # windows
Then mention that it's only for tools, not libs. Only install libs in venv. Some tools also should just not be installed at the system level such as jupyter or pytest because they depends on their env.

Cause: installing with admin rights can destroy your python installation. Also, pip may not be in the PATH, or be attached to the wrong version of Python. It's also because we are twisting a lib packaging tool into providing programs.

This is not specific to python. Node had to introduce a whole know command, npx, to solve the same problem, and the ones bellow. It actually takes a command name, and if it doesn't exist locally, but is registered on npm, download the package that seems to contain it, install it in a temp folder with all its deps, then immediately attempt to run it in isolation.

4 - Use tools correctly

It's another lie from docs and tutorials. If you install a tool, just calling the command may fail.

If you installed a command outside of a venv like above, then you should call it using "-m". E.G:

python3.6 -m black # or py -3.6 -m black

Cause: again, you don't know how the PATH is setup, so there is no guaranty that the command will be available, or ran from the proper python version. People can have completely messed up machines and there is nothing you can do about it. So don't depend on the PATH.

5 - Use venv correctly

The solution to all those shenanigans are the venv. Once you are in a venv, you don't need to tell the version of python, you don't need "py", "-m" or "--user". You can call commands directly. You can just use "python".

But first, people need venv installed. It's installed by default on Windows and Mac, but on linux, it's often a package to install like python3-venv, python3-pip or python3-setuptool.

Do not "pip install virtualenv": people will get confused between the tools.

So, make them create a venv: "pythonX.Y -m venv name_of_the_venv" (or py -X.Y).

Show them how to use the python/pip from the venv WITHOUT activating it, so that they understand how it works and show them the that unix have ./bin and windows ./Scripts.

Then show activation, and tell them to install pytest/jupyter and Co inside. Show them that it solves all the previous problems, so that they are motivated to use them.

Tell them to NOT put their code in the venv folder. And that they can't move or rename a venv. Show them "pip freeze > requirements.txt" + "pip install -r requirements.txt" as an alternative.

Cause: historically python didn't have the venv module, and people used to pip install virtualenv, which mean we still have docs about it, and the name stuck. Having a long history makes things complicated. And once again, the differences between Windows and Unix bites us, but that's the cost of being portable. It's not Python-specific. The fact you can't move a venv is an artefact of the venv design that the community never solved.

# Variant

People may want or need to use anaconda or the python embedded in a system (blender, qgis, etc). Then it's a whole different cycle of problems and solutions, so I won't talk about it here, this post is long enought.

Again, Python diversity is playing against it: you don't have one popular python distrib like with nodejs or cRuby. You also have commercial Python distribs, and some are used a lot in the corporate world.

Diversity make things more resilient and encourage innovation. But it makes thing harder.

# Pyproject and setup.cfg

They have nothing to do with all that. They are useful if you want to _produce_ a package to share your code with other devs.

comment 6y ago · link · parent

The setup is easy and the video works very well, including with many participants.

That's it.

There is nothing else. They managed to do one thing well.

This thing that skype used to do correctly but now don't.

This thing that no other free softwares seems to be able to manage correctly either. Not teams. Not hangout. Not Jitsi or BBB.

It makes you think.

comment 6y ago · link · parent

It's not a metaphor. It's a sell pitch.

comment 6y ago · link · parent

It is, but the whole experience go together. Just like booting flickers is caused by many problems, but it is about one experience.

comment 6y ago · link · parent

Oh it did become better.

I've been using linux for 15 years. It's better in every way.

My mother has been using Ubuntu for 7 years now. It would have been impossible in the early 2000.

It is better. It is productive. It is even a good experience. I'm no a masochist, I buy and use proprietary software. I use Linux because I want to.

I'm not just not blind to it's many shortcommins.

Last week I used Windows with a client. I had to disable Windows update because it was eating all the Ram. Some people are literally buying a new mac because the mechanical keyboard is unusable on some models.

There are systems you complain about. And systems nobody use.

comment 6y ago · link · parent

Yes, it's imperfect and irritating in many ways. Many other actually (BT, Wifi, battery life, they all have their problems).

But your alternative is one totally locked on ecosystem and one provided with embedded spywares.

It's good enough, and since we are not giving millions of dollars to the editors like we do with products disrespecting us, I understand we can't ask for perfection.

comment 6y ago · link · parent

+1. I'll add:

* The screen locks, unlock, but the network card cannot wake up anymore and requires a reboot.

* The screen locks, let you enter things, but doesn't seem to react, then suddenly, replay all the things for 20 seconds in 1 seconds, and displays an error message

* the screen locks, but you can see the unlock screen for a few seconds when you wake the laptop up

comment 6y ago · link · parent

So, the entire nation uses whatsapp and gmail, the services made by the biggest data collectors on earth, known to have taken part of the PRIMS program, that send record of said data to private 3rd party for analysis, to have people inside abusing the access to that data, and they focus on zoom ?

I mean, it's good that people suddenly care about privacy, but it's like raising awareness on acne while Covid19 is out there.

comment 6y ago · link · parent

Dolt is not Git for data.

Git take existing files, and allow you to version them.

Git for data would take existing tables or rows, and allow you to version them.

A uniform, drop in, open source way to have an history or row, merge them, restore them, etc. that works for Postgres, Mysql or Oracle in the same way. And is compatible with migrations.

You can have an history if you use big table or couchdb, not need for Dolt if it's about using a specific product.

comment 6y ago · link · parent

Gonna add test with hello world to see vm startup time.

comment 6y ago · link · parent

As stated: "the times varied a lot because my machine is not setup for a clean benchmark"

So this is not a benchmark. Just a fun observation of a trend. A proper benchmark would require to have a dedicated machine with no other softwares running, hyperthreading off and run each of them a 100 times, without fs cache.

EDIT: gonna edit the original post with hyperfine results.

comment 6y ago · link · parent

I took it for a ride

They all list all files recursively in a sync fashion, from the node_modules dir (like in the benchmark), excluding dirs, and print a total count.

Here are the results calculated with hyperfine (https://github.com/sharkdp/hyperfine):

    hyperfine "bash test.sh" --warmup 5
    Benchmark #1: bash test.sh
    Time (mean ± σ):       7.5 ms ±   0.5 ms    [User: 4.5 ms, System: 4.2 ms]
    Range (min … max):     6.9 ms …  10.5 ms    332 runs

    hyperfine "perl test.pl" --warmup 5
    Benchmark #1: perl test.pl
    Time (mean ± σ):      25.6 ms ±   1.2 ms    [User: 16.8 ms, System: 8.8 ms]
    Range (min … max):    24.0 ms …  30.8 ms    97 runs

    hyperfine "python3.7 test.py" --warmup 5
    Benchmark #1: python3.7 test.py
    Time (mean ± σ):      43.4 ms ±   1.4 ms    [User: 32.6 ms, System: 10.9 ms]
    Range (min … max):    40.9 ms …  46.8 ms    66 runs
    
    hyperfine "ruby test.rb" --warmup 5
    Benchmark #1: ruby test.rb
    Time (mean ± σ):      66.5 ms ±   2.0 ms    [User: 52.1 ms, System: 14.4 ms]
    Range (min … max):    63.2 ms …  70.3 ms    42 runs

    hyperfine "node test.js" --warmup 5
    Benchmark #1: node test.js
    Time (mean ± σ):      83.7 ms ±   4.0 ms    [User: 74.7 ms, System: 15.6 ms]
    Range (min … max):    79.4 ms …  95.3 ms    36 runs
Here are the results of an hello world with each runtime for comparison:

    hyperfine "bash test.sh" --warmup 5
    Benchmark #1: bash test.sh
    Time (mean ± σ):       1.2 ms ±   0.3 ms    [User: 1.1 ms, System: 0.3 ms]
    Range (min … max):     0.9 ms …   3.8 ms    1521 runs

    hyperfine "perl test.pl" --warmup 5
    Benchmark #1: perl test.pl
    Time (mean ± σ):       1.3 ms ±   0.3 ms    [User: 1.3 ms, System: 0.3 ms]
    Range (min … max):     1.0 ms …   5.3 ms    1103 runs

    hyperfine "python3.7 test.py" --warmup 5
    Benchmark #1: python3.7 test.py
    Time (mean ± σ):      19.5 ms ±   0.9 ms    [User: 16.2 ms, System: 3.4 ms]
    Range (min … max):    18.3 ms …  23.7 ms    144 runs

    hyperfine "ruby test.rb" --warmup 5
    Benchmark #1: ruby test.rb
    Time (mean ± σ):      55.2 ms ±   2.2 ms    [User: 47.2 ms, System: 8.1 ms]
    Range (min … max):    52.2 ms …  61.9 ms    51 runs
    
    hyperfine "node test.js" --warmup 5
    Benchmark #1: node test.js
    Time (mean ± σ):      55.4 ms ±   1.8 ms    [User: 49.5 ms, System: 7.0 ms]
    Range (min … max):    53.0 ms …  60.0 ms    53 runs
Now, my machine is not setup for a clean benchmark. The disk cache is warmed up. Hyperthreading is on. Other softwares are running.

Plus the scripts all found a slightly different number of files :) I suspect they all treat symlinks/dotted dirs differently, and I didn't take the time to normalize. Although I don't think this makes up for the difference.

Still the result is a bit interesting. The non JS tests are not using any 3rd party libs. Ruby and Node seems to have the same cost for VM startup.

I'm quite surprised that node is last frankly, especially on a uber optimized code. I'm expecting V8 code to be blazing fast as it's Google made and C++.

comment 6y ago · link · parent

Sure.

And now it has been better for the last 5 years, and does solve the problems it intended to solve.

comment 6y ago · link · parent

It started to be possible with Python 3.3, which came out 8 years ago.

We are at Python 3.8.

Python 3 has been around for 13 years, during which Python 2.7 was still supported.

comment 6y ago · link · parent

The first versions of python 3 were indeed, not suitable for serious work. Python 3 started to be usable from 3.3, interesting from 3.4, comfortable from 3.5, and objectively way better than 2.7 from 3.6.

It's not a surprise, as most softwares need iterations to get get good. Python 2.7 has not started as the amazing tool it is now, and as I started my career with 2.4, you remember some funny stuff.

This is why Python 2.7 was kept around for 13 years after Python 3 first came out.

Now, 3.6 came out in 2016. It solves many issues 2.7 had, and add tons of goodies. It's very ergonomic, can be installed easily. It's a great software.

It's 2020, let's enjoy the goodness of Python 3.

comment 6y ago · link · parent

I failed to mention that it's only useful to do this manually if you need to decode path with mixed encodings, or share said path with the rest of the world.

If all you need is to work with arbitrary mixed bags of file names, you can just pass "str", and Python will use automatically and transparently surrogateescape everywhere.

comment 6y ago · link · parent

Rust is fantastically expressive for a low level language.

And modern C++ is not 15 years old C++. You have auto, lambda, etc. I just think it's silly to try to pretend to be more expressive than scripting languages.

It's like Schwarzenegger trying to pretend it's as flexible as gymnast. What for? The guy is amazing at what he does.

comment 6y ago · link · parent

Python 3 promotes the most likely scenario: you are on a modern system with normal looking filenames.

It would be unwise to design an API that promotes a niche need like dealing with a legacy file system with corrupted file names. This is what Python 3 fixed, making the easy things easy, and the complicated things possible, not the other way around.

But Python 3 is absolutely up to the task of handling legacy file systems with random encoding mixed in, you just need to tell it explicitly you are doing so.

Let's create a file with a completely garbage name, made of random bytes, which is allowed on Unix:

    >>> import os, sys
    >>> sys.version_info          
    sys.version_info(major=3, minor=7, micro=5, releaselevel='final', serial=0)
    >>> with open(os.urandom(32), 'wb') as f: 
    ...     f.write(os.urandom(200)) 
If you pass bytes to any file system function, it will return file names as bytes:

    >>> filename = os.listdir(b'.')[0]
    >>> type(filename)
    <class 'bytes'>
    >>> filename[:10]   
    b'\xf8-U\xa5\x1dq\xad?\xbf\xa2'
And you can just open that:

    >>> data = open(filename, 'rb').read() 
    >>> data[:10]
    b'E\x05\xce*M \xf5\xfeK\x18'
    >>> type(data)
    <class 'bytes'>
You do exactly the same as what you did with Python 2, and treat the files as raw bytes entirely, without thinking about the content.

Some API in Python require text. If you want to pass the file names to those API, you can use surrogate escape, which let you convert back and forth between arbitrary bytes and utf8 text, without loosing information:

    >>> as_text = filename.decode('utf8', errors='surrogateescape')
    >>> as_text[:10]
    '\udcf8-U\udca5\x1dq\udcad?\udcbf\udca2'
    >>> type(as_text)
    <class 'str'>
    >>> as_text.encode('utf8',  errors='surrogateescape') == filename
    True
This is a good thing, it forces the dev to be explicit about the places in your code where you are dealing with a specific scenario. It also makes you pay the price of doing so opt in, not opt out.

If you have to do a robust version of this with Python 2, you will have to do that anyway: at some point mixed encoding will bite you if you don't have a neutral representation for them. Python 2 gave you the illusion of robustness, because it said "yes" to most operations.

I remember quite well that a lot of Python 2 programs didn't work in Europe because your user directory would contain your name, which could be non ascii. Python 2 programs are opt in to deal with it. It's the opposite philosophy, and caused so many crashes.

comment 6y ago · link · parent

There are people still using Windows XP.

There are programs still using COBOL.

That's life in IT.

comment 6y ago · link · parent

This is getting ridiculous.

We went from:

> many Python projects have way more lines of code than equivalent C++ projects

To:

> It's a bit longer in C++ but frankly not by that much

With the proof being literally __twice__ more characters, with one line being more than a 100 characters long.

I understand that C++ doesn't have a native JSON lib, and sorting is a bit out there, but giving 3rd party lib access to Python feels like cheating:

    import pandas as pd
    agenda = pd.read_json("agenda.json", convert_dates=["hired"])
    for _, (name, age, hired, emails) in agenda.sort_values("name").iterrows():
        print(f"{name} ({age}) - {hired:%d/%m/%y}:")
        for email in emails:
            print(f" - {email}")
I mean, I can also create a lib that does the entire script, install it, and just do 'import answernh; answerhn.print_json("agenda.json")'

Now again, this is not so say "Python is better than C++". That's not the point.

If you want to write a game engine, C++ makes sense, verbosity doesn't matter, and you don't want the Python GC to kick in. If you want to iterate on your Saas product API quickly, it's probably not the best choice.

Why pretend otherwise? What the point of stating the sky is red?

comment 6y ago · link · parent

And Rust is very, very expressive and concise for a bare metal language. Serde is a beautiful thing.

comment 6y ago · link · parent

> Once you've written sufficient unit tests to prove your code works as well as a C++ equivalent does just by compiling

You mean in the same way C++ dev write tests to prove that all their code has no memory error which you get in Python for free ?

Except:

- tests are way shorter to write in python than in C++

- C++ devs often write zero tests for their code, just like python devs

- python duck typing + REPL means compiler checks are rarely necessary

- if you need to be type checks, you use type hints in python, which even then is still less verbose than c++

> I'd also argue that operator overloading etc lets C++ be just as expressive as Python, the libraries just need to be designed with that in mind.

Ok, let's say you have this json:

    [{
        "name": "Kévin",
        "age": 23,
        "hired": "2005-06-03 02:12:33",
        "emails": ["kevin@foo.com", "kevin@bar.com"]
    }, {
    }, {
        "name": "Joël",
        "age": 32,
        "hired": "2003-01-02 12:32:11",
        "emails": ["joel@foo.com", "joel@bar.com"]
    },
    ... other entries
    ]

It's very simple. Very basic. There is no trick in there: it's standard utf8, well formed, no missing value.

You want to print people details in alphabetical order this way:

    Joël (32) - 02/01/03:
    - joel@foo.com
    - joel@bar.com
    Kévin (23) - 03/06/05:
    - kevin@foo.com
    - kevin@bar.com
    ... other entries
This is a 1rst year of college exercise. Nothing remotely complicated. I'm not choosing some fancy machine learning or data processing stuff for which Python has magic libs. Every language can do that easily.

In Python 3.7, which is already 2 years old, the code would be:

    import json
    import datetime as dt

    with open("agenda.json") as fd:

        agenda = sorted(json.load(fd), key=lambda people: people["name"])

        for people in agenda:

            hired = dt.datetime.fromisoformat(people["hired"])
            print(f'{people["name"]} ({people["age"]}) - {hired:%d/%m/%y}:')

            for email in people["emails"]:
                print(f" - {email}")
The entire script is there. There is no trick. This is not a code golf version of of it; I could make it shorter. It really is standard Python. There is no 3rd party lib either.

It's not specific to Python, you would get this expressiveness with Ruby or Perl.

I don't see in which world you would get that in regular, honest to god, day to day, portable C++.

You have to declare types, many includes, you'll have headers and a main function. You have the memory and references to manage.

It doesn't make C++ a bad language.

It doesn't make python a better language.

The C++ version will take way less RAM than the Python version for example.

It's just the nature of those languages implies that.

comment 6y ago · link · parent

I've been coding in Python for 15 years, and from what I see in the numerous places I get to work, yes, it worked.

It's just that aghast people are the most vocal. You don't hear the 90% of people that are happy. They don't take the time to speak up. But the unhappy complain all the time.

comment 6y ago · link · parent

> many Python projects have way more lines of code than equivalent C++ projects.

That is mathematically impossible. Even if the syntaxes were exactly the same (which they are not, python syntax is on average shorter), the low level nature of C++ requires your code to do operations that Python does need to do, such as memory management.

It's like stating the sky is red.

comment 6y ago · link · parent

Population was balancing itself for millions of year. We call overpopulation a population big enough to annoy us.

comment 6y ago · link · parent

The reasons the transitions worked were that:

- the languages were not that different, so no need to learn the new version

- python core devs gave 10 years to make the transition. Then extended it.

- it was possible to write code running on python 2 and 3

- python is very expressive, hence the code base have way less numbers of lines than in C++

- python cared only about one implementation, Cpython. The rest of the world needed to follow. Some didn't, like Jython and stackless, and the community didn't blink.

Despite all that, the transition was very painful.

comment 6y ago · link · parent

It would be like saying you can't have high level languages because assembly have only a few limited combinations of registers. You can always abstract things away.

In fact, you are making the assumption that there is no more generalist logical concepts we can discover that can abstract or merge what now appears to be conflicting paradigms.

I imagine people said that to Argand. Nah, you can't do that sqrt(-1) thing, you'll run into contradictions.

Given that we have been at the task for less than a century, which is like 1 minute of human history, I'm not inclined to such categorical rejection of the possibility.

comment 6y ago · link · parent

Most popular FOSS project do not follow this model at all.

Linux, VLC, LibreOffice, Posgres, Firefox, Chrome, VSCode...

Sure, you can see part of the communication and have an input channel, but unless you are part of the inner circle, or have some influence over it, you won't be able to see everything, weigh in, vote or determine anything.

Which is sane: the number of competent people is limited. The ones inside the circle can't spend their time fighting with the debate from outside. They have to get a way to filter information, take decision and act.

People stating differently have either never been part of a successful big project, or have been blind by the discourse that their project is, while in fact, there is an informal inner circle despite their institution stating otherwise.

It's like when you meet a "leaderless" group. If it's a small group, it works. If it's a big group, either it doesn't, or an informal hierarchy with leaders exist but nobody acknowledge it out of ignorance or idealism.

comment 6y ago · link · parent

A programming language is not tool, like a hammer, with which you build a house. It's a truck full of toolboxes, containing sets of tools made to work in harmony, that you use to build parts of the house that requires a human to deal with it manually.
1
171172173
184