Python Forum
Do packages really require "__init__.py" ?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Do packages really require "__init__.py" ?
#3
(Feb-14-2019, 04:19 PM)denis_beurive Wrote: Python recognises "package" as being a package event without the presence of the file "__init__.py".

Do I misunderstand something ?
No,from Python 3.3+ supports Implicit Namespace Packages that allows to create a package without an __init__.py file.
This however only applies to empty __init__.py files.
So empty __init__.py files are no longer necessary and can be omitted.

To give a example,i always have one __init__.py that has content to lift sub modules,
this to avoid long import statement and make it easier for users of package.
my_pack\
|-- __init__.py
  color\
  |-- base_color.py
    gradient\    
    |-- gradient.py
__init__.py
from .color import base_color
from .color.gradient import gradient
base_color.py
def red():
    return 'rgb(255, 0, 0)'
gradient.py
def hsl_value():
    return 'rgba(255, 100, 50, 1.0)'
As i have lifted with __init__.py there is no need to say color.gradient.hsl_value() when import.
Usage:
λ ptpython
>>> from my_pack import base_color, gradient

>>> base_color.red()
'rgb(255, 0, 0)'


>>> gradient.hsl_value()
'rgba(255, 100, 50, 1.0)'
And stop using very old %s string formatting.
>>> for word in 'f-strings are awesome'.split():
...     print(f'{word.upper():~^20}')
~~~~~F-STRINGS~~~~~~
~~~~~~~~ARE~~~~~~~~~
~~~~~~AWESOME~~~~~~~

>>> # f-strings support any Python expressions inside the curly braces
>>> name = 'f-string'
>>> print(f"My cool string is called {name.upper()}.")
My cool string is called F-STRING.
 
>>> a, b = 5, 7
>>> f'{a}/{b} = {a/b:.2}'
'5/7 = 0.71'
Reply


Messages In This Thread
RE: Do packages really require "__init__.py" ? - by snippsat - Feb-15-2019, 03:59 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Why doesn't list require global keyword? johnywhy 9 1,099 Jan-15-2024, 11:47 PM
Last Post: sgrey
  Pattern Require Last Line Print() why? Harshil 4 2,520 Aug-08-2020, 04:54 PM
Last Post: Harshil
  Require Some Suggestions gouravlal 2 1,953 Jul-27-2020, 06:14 AM
Last Post: gouravlal
  Do you require imports used in other files? Panda 1 2,573 Jul-14-2018, 02:30 PM
Last Post: gontajones
  Why does function print require bracket for text? richardm55 2 3,062 May-23-2018, 07:30 PM
Last Post: buran
  I Require some help for project idea...FaceRecognizer Door actived JavierGTZ 0 2,549 Aug-18-2017, 04:45 PM
Last Post: JavierGTZ
  Why is there an __init__ statement within the __init__ definition iFunKtion 7 6,168 Feb-06-2017, 07:31 PM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020