home.social

#pythonic — Public Fediverse posts

Live and recent posts from across the Fediverse tagged #pythonic, aggregated by home.social.

fetched live
  1. SOLID в Python без воды

    Открываешь чужой код на Python, а там — Java. Абстрактные базовые классы в местах, где хватило бы простой функции, фабрики фабрик и нагромождение паттернов, усложняющих чтение бизнес-логики. Знакомая картина? Многие разработчики механически переносят архитектурные привычки из строго типизированных языков в Python, создавая переусложненный неидиоматичный код. В этой статье мы возьмем классические правила SOLID и переведем их на язык динамической типизации (Pythonic way). Разберем на реальных примерах, где принципы спасают проект, а где слепое следование им скатывается в карго-культ.

    habr.com/ru/articles/1045294/

    #Python #SOLID #ООП #архитектура #рефакторинг #паттерны_проектирования #чистый_код #pythonic #duck_typing

  2. 🚫🤣 Roto: The revolutionary #scripting #language nobody asked for, where semicolons are banished to the shadow realm! Because who needs tiny dots and squiggles when you can create #chaos with #Pythonic ambiguity? 👏🥴
    terts.dev/blog/no-semicolons-n #Roto #Ambiguity #Tech #Humor #Coding #HackerNews #ngated

  3. 🚫🤣 Roto: The revolutionary #scripting #language nobody asked for, where semicolons are banished to the shadow realm! Because who needs tiny dots and squiggles when you can create #chaos with #Pythonic ambiguity? 👏🥴
    terts.dev/blog/no-semicolons-n #Roto #Ambiguity #Tech #Humor #Coding #HackerNews #ngated

  4. Знакомьтесь, Ричард Джонс (цикл заметок о выдающихся питонистах)

    PyPI — централизованный каталог Python-пакетов. Сегодня в нем более 865 тысяч проектов общим весом 36 терабайт . PyPI создал Ричард Джонс . В октябре 2002-го, в электричке, по дороге на работу в Мельбурн. Будет интересно

    habr.com/ru/articles/1007150/

    #python #pythonic #питонист #Ричард_Джонс #история #история_it #история_ит

  5. Знакомьтесь, Эндрю Кучлинг (цикл заметок о выдающихся питонистах)

    Замысел в том, чтобы написать цикл о 10 программистах, чьи имена не особо примелькались, но чьи заслуги невозможно переоценить. Начну я этот цикл с Эндрю Кучлинга (A.M. Kuchling) . Я всегда знал его как автора официального туториала по регуляркам в питоне, пожалуй, лучшего по теме. Но масштаб этого человека куда больше.

    habr.com/ru/articles/1006200/

    #python #pythonic #история #Эндрю_Кучлинг #питонисты

  6. @JessTheUnstill
    I'm working on a programming language, going by the name of #Rocket.

    It's supposed to be #Pythonic, but compilable.
    Concretely, that means you can modify types, modules, etc. at compile time (e.g. inject another method into a class, replace a method with a wrapped one, create a class dynamically, etc.), but not at runtime.

    Still in the early stages, though :blob_grinning_sweat:

  7. @JessTheUnstill
    I'm working on a programming language, going by the name of #Rocket.

    It's supposed to be #Pythonic, but compilable.
    Concretely, that means you can modify types, modules, etc. at compile time (e.g. inject another method into a class, replace a method with a wrapped one, create a class dynamically, etc.), but not at runtime.

    Still in the early stages, though :blob_grinning_sweat:

  8. I am "#Python is the batteries-included language, unlike Perl or TCL!" years old, and that has aged like a prawn cocktail. The standard library is chok full of awkward "un-#Pythonic" legacy code that only exists because changing it would break backward-compatibility.

    But Python 3.0 *gleefully* broke backward-compatibility! They broke `print "Hello, world."` which is the most-written Python code in history!

    So for my money, Python 4.0 should be a release that gets rid of boat anchors like HTTPlib, and pushes that stuff into a `from deadbatteries import ...` compatibility library for the folks who absolutely need it.

    You could do statistical analysis of `requirements.txt` files out on the Internet and see what replaces-the-horrible-stdlib-version packages are imported the most. You can then mainline the winning replacements, or figure out what APIs or features everyone is reaching for when they import some new dependency and reimplement that. It doesn't matter if you NIH it, re-do the API on existing library code, or promote a third-party project to Python core library status.

    Python's dependency resolution tooling is not just a mess: it's a dozen independently-maintained messes that compound the problem. I want to go back to being able to actually rely on the standard library. I do my best now, but the level of jank is only getting worse as the years drag on, and that prawn cocktail is absolutely pongin'.

  9. I am "#Python is the batteries-included language, unlike Perl or TCL!" years old, and that has aged like a prawn cocktail. The standard library is chok full of awkward "un-#Pythonic" legacy code that only exists because changing it would break backward-compatibility.

    But Python 3.0 *gleefully* broke backward-compatibility! They broke `print "Hello, world."` which is the most-written Python code in history!

    So for my money, Python 4.0 should be a release that gets rid of boat anchors like HTTPlib, and pushes that stuff into a `from deadbatteries import ...` compatibility library for the folks who absolutely need it.

    You could do statistical analysis of `requirements.txt` files out on the Internet and see what replaces-the-horrible-stdlib-version packages are imported the most. You can then mainline the winning replacements, or figure out what APIs or features everyone is reaching for when they import some new dependency and reimplement that. It doesn't matter if you NIH it, re-do the API on existing library code, or promote a third-party project to Python core library status.

    Python's dependency resolution tooling is not just a mess: it's a dozen independently-maintained messes that compound the problem. I want to go back to being able to actually rely on the standard library. I do my best now, but the level of jank is only getting worse as the years drag on, and that prawn cocktail is absolutely pongin'.

  10. For the Python programmers under you who wanted to make your app print, you probably have used pyCUPS to talk with the printing system. Perhaps you have also seen that it is not well maintained, not keeping pace with new APIs. Problem was its design, being a maintenance nightmare.

    But for libcups3 it gets much better, thanks to the most Pythonic GSoC contributor we ever had, and CFFI:

    soumyadghosh.github.io/website

    Thanks @soumyadghosh

    #OpenPrinting #Python #Pythonic #CFFI #CUPS #GSoC #GSoC2025

  11. For the Python programmers under you who wanted to make your app print, you probably have used pyCUPS to talk with the printing system. Perhaps you have also seen that it is not well maintained, not keeping pace with new APIs. Problem was its design, being a maintenance nightmare.

    But for libcups3 it gets much better, thanks to the most Pythonic GSoC contributor we ever had, and CFFI:

    soumyadghosh.github.io/website

    Thanks @soumyadghosh

    #OpenPrinting #Python #Pythonic #CFFI #CUPS #GSoC #GSoC2025

  12. DumPy: Because embracing your inner dolt is the new #Pythonic way of life. 🤪📉 Want to run fast on #GPUs without a single brain cell firing? This is the #guide for you, where "thinking" is officially a deprecated feature. 😂🧠
    dynomight.net/dumpy/ #DumPy #humor #fun #HackerNews #ngated

  13. DumPy: Because embracing your inner dolt is the new #Pythonic way of life. 🤪📉 Want to run fast on #GPUs without a single brain cell firing? This is the #guide for you, where "thinking" is officially a deprecated feature. 😂🧠
    dynomight.net/dumpy/ #DumPy #humor #fun #HackerNews #ngated

  14. Ursina: Создание умных NPC через поведенческие деревья (Часть 2)

    В первой части мы разобрали основы Ursina и создали простую 3D-игру. Теперь перейдем к более сложной механике — искусственному интеллекту для NPC с помощью поведенческих деревьев (Behavior Trees).

    habr.com/ru/articles/898360/

    #ursina_engine #ursina #python #python3 #python_3 #pythonic #python_class #python_tutor #game_development #gamedev

  15. [Перевод] Чистый код в Python

    Всем привет! Это перевод статьи Clean Code in Python . В данной статье Nik Tomazic рассказывает о чистом коде, его преимуществах, различных стандартах и принципах, но что самое главное– он дает общие рекомендации по написанию чистого кода. Прочитав данную статью в оригинале, я понял, что это именно то, что я хотел бы прочитать в самом начале своего пути разработки на Python. Именно это и вдохновило меня на создание первого перевода, а вместе с этим, и первой публикации на Хабре.

    habr.com/ru/articles/877118/

    #чистый_код_Python #PEP_8 #Pythonic #DRY #SOLID #форматирование_кода #модульность_в_Python #Дзен_Python #python

  16. @villares @AlSweigart @nedbat
    Thanks! Although it may be small, it's not exactly #Pythonic. I also just realized that it might not be very efficient. Maybe we should check with `timeit`.

  17. @villares @AlSweigart @nedbat
    Thanks! Although it may be small, it's not exactly #Pythonic. I also just realized that it might not be very efficient. Maybe we should check with `timeit`.

  18. @AlSweigart @nedbat You inspired me to hack a way to ensure `a`, `b`, and `c` are distinct. I came up with…

    ```
    len(set((a, b, c))) == 3
    ```

    I suspect that's bordering on obfuscated code. Probably not #Pythonic.

    #Python

  19. @AlSweigart @nedbat You inspired me to hack a way to ensure `a`, `b`, and `c` are distinct. I came up with…

    ```
    len(set((a, b, c))) == 3
    ```

    I suspect that's bordering on obfuscated code. Probably not #Pythonic.

    #Python

  20. Простое управление настройками приложения в проекте на django

    Как добавить кучу настроек для администратора в свой проект на django без дополнительных сервисов feature-toggle и потом в них не потеряться.

    habr.com/ru/articles/869432/

    #настройки #конфиги #python #pythonic #featuretoggle

  21. @AliveDevil

    Oof. Yes, this code

    > if self._unique_id == 'none':

    is glaringly un-#Pythonic to this reader.

    I venture to say it's even a mistake, because the only place that attribute gets set is earlier:

    > self._unique_id = kwargs.get('unique_id')

    which will return the `None` object if 'unique_id' is not in `kwargs`.

    So that conditional test should just be using the normal Pythonic:

    > if self._unique_id is None:

    Which is why the `dict.get` method returns `None` when the key isn't found.

  22. @AliveDevil

    Oof. Yes, this code

    > if self._unique_id == 'none':

    is glaringly un-#Pythonic to this reader.

    I venture to say it's even a mistake, because the only place that attribute gets set is earlier:

    > self._unique_id = kwargs.get('unique_id')

    which will return the `None` object if 'unique_id' is not in `kwargs`.

    So that conditional test should just be using the normal Pythonic:

    > if self._unique_id is None:

    Which is why the `dict.get` method returns `None` when the key isn't found.

  23. Ok, my new mission is convincing people, especially those involved with @rOpenSci, that they are indeed research software engineers and that they should get involved in the disproportionately (in my opinion) @us_rse

  24. Ok, my new mission is convincing #rstats people, especially those involved with @rOpenSci, that they are indeed research software engineers and that they should get involved in the disproportionately #pythonic (in my opinion) @us_rse

  25. 10 кубиков синтаксического сахара

    В питоне очень много полезного и интересного синтаксического сахара. Настолько много, что у неподготовленных пользователей может случиться сахарный диабет. Здесь вы увидите несколько уникального для питона синтаксического сахара, его примеры правильного и неправильного применения.

    habr.com/ru/articles/839558/

    #синтаксический_сахар #синтаксис #языковые_конструкции #pythonic

  26. if you are taking python interview for a 4-5+ yr experience developer wiho has all the modern fancy packages listed out in their CV but they can't write good #pythonic code with just the language and no external dependencies... #aita? for never asking textbook questions but creating simple coding exercises which require no leet level algorithms etiher? not a single candidate went through without struggling. i have stopped believing in the fancy packages they are putting in python developer CVs.
  27. How should I read #credentials into a #python script?

    What did you choose and why?

    Is there the one #pythonic way?

    What is proof for future (cronjob, container, VM) not only if I start it manually?

    #fedihelp

  28. How should I read #credentials into a #python script?

    What did you choose and why?

    Is there the one #pythonic way?

    What is proof for future (cronjob, container, VM) not only if I start it manually?

    #fedihelp

  29. @skimlines @cs

    It's fine for #lists - but it's not the most "#Pythonic" way to do this, at least for lists. Like some other built-in objects, lists have a method `.copy()` which does what it says - returns a #copy of the #object. That's more obvious than using `...[:]` when reading the code, so that tends to be the preferred way in Python.

    Unfortunately, #tuples don't have .copy(). They do support [:]. 🤷

    [...]

  30. @skimlines @cs

    It's fine for #lists - but it's not the most "#Pythonic" way to do this, at least for lists. Like some other built-in objects, lists have a method `.copy()` which does what it says - returns a #copy of the #object. That's more obvious than using `...[:]` when reading the code, so that tends to be the preferred way in Python.

    Unfortunately, #tuples don't have .copy(). They do support [:]. 🤷

    [...]

  31. @cazabon

    I was trying to test performance to see which is better.

    #Pythonic

  32. @cazabon

    I was trying to test performance to see which is better.

    #Pythonic

  33. @encthenet

    Of course, you didn't say why you didn't want to use the most #Pythonic of the possibilities...

    `"".join([list of strings])`

    ?

  34. @encthenet

    Of course, you didn't say why you didn't want to use the most #Pythonic of the possibilities...

    `"".join([list of strings])`

    ?

  35. Hey #Python folks (and I'm looking especially at you @treyhunner) what's the most #pythonic way to “write to file if it exists, else create it and then write to it”?

    `open(filename, ‘x’)` only works once, AIUI. I want a code snippet (or library!) that will work every time

  36. While working with #Python, I miss being able to use an assignment statement as an expression, particularly when constructing a while loop.

    Example:
    while ((myDate = NextFOM (myDate)) <= EndDate):
    print ("First of Month", myDate)

    From what I've read, it looks like a #Pythonic way to rewrite the above code looks like this:

    while True:
    myDate = NextFOM (myDate)
    if myDate > EndDate:
    break
    print ("First of Month", myDate)

  37. @spencer @petrem @jzik
    It is just not very (readable) so I was just wondering if it was just my background or others find it hard to read too :)