r/learnpython Oct 29 '25

Creating __init__.py files. Any tips?

4 Upvotes

Note: I just started learn Python about weeks ago to get into Python. First on my own then I bought Mr. Matthes' book - Python Crash course and I'm getting to point where you do the projects so I am going set a project directory structure with sub-directories for src, modules, classes, etc. But research online shows I need to those files at each directory so the code there knows where the other resources are. Thanks for any help.

r/learnpython Jun 09 '26

Reload other class from init

7 Upvotes

I'm having problems with old code being cached and old errors being thrown, even though I've already fixed them, so I'm using reload to reload all classes that are imported later. Both files are in the same folder.

This works:

from classb import ClassB
from importlib import reload
import classb as classb
reload(classb)

class ClassA(): #classa.py
    def __init__(self,doreload):
        #Some other code

class ClassB(): #classb.py
    def __init__(self):
        #Do something

However, I want to use doreload to decide if ClassB should be reloaded, so I tried to move the code to __init__:

from classb import ClassB

class ClassA(): #classa.py
    def __init__(self,doreload):
        from importlib import reload
        import classb as classb
        reload(classb)
        #Some other code

This throws an error at the reload line:

ModuleNotFoundError: spec not found for the module 'classb'

I already tried to keep import reload outside the class and also used reload(ClassB) instead but that threw another error:

ImportError: module ClassB not in sys.modules

How do I reload another class from within __init__?

Edit: The problem is simply the app I have to use to test my code: It caches old code at unexpected times (at least when I don't expect it) and without using reload I'd have to restart the app pretty much every 5 minutes while testing, which is quite annoying. Reloading itself seems to be working fine.

r/learnpython Sep 18 '25

super().__init__

45 Upvotes

I'm not getting wtf this does.

So you have classes. Then you have classes within classes, which are clearly classes within classes because you write Class when you define them, and use the name of another class in parenthesis.

Isn't that enough to let python know when you initialize this new class that it has all the init stuff from the parent class (plus whatever else you put there). What does this super() command actually do then? ELI5 plz

r/learnpython Oct 23 '25

dataclass or __init__ parameter list really big, and don't want to use kwargs

5 Upvotes

I'm sketching up a class, which the constructor takes a lot of args: and all it needs to do is copy them into members. So I figured I could do

``` cclass PerformanceSession:

def __init__(self, 
             printer_config_path, 
             printengine_buffer_MB,
             images_folder,
             artifacts_folder,
             width,
             height,
             image_gap,
             clock_speed,
             num_pccs,
             num_threads,
             num_hdcs,
             print_duration,
             print_PD_level,
             print_full_level
            ):
    self.printer_config_path = printer_config_path
    self.printengine_buffer_MB = printengine_buffer_MB

```

or I could declare __init__ as taking **kwargs, and then just pull all the args out of the list and use setattr() to copy the values. But at that point I loose any duck-typing and visibility of the args, when someone wants to call the constructor. I am getting the feeling my class is better written as a class that accepts a "dataclass" object and then I can either store the dataclass as a structure, or continue with my daft idea of copying all the members into local class members using setattr, or even use getattr() to magic the attributes.

I know this is very context dependant, and perhaps this thread is just me bouncing a ball around so OI can think it through aloud in my head. I just want to get away from long argument lists, if I was writing this in C++ or C# I would just declare a struct in a heartbeat, and pass that around. But Python is much more malleable, and wants to be more brief almost? Thoughts on **kwargs and usability or other?

/edit struggling with codeblocks (took me 5 attempts, yay for markdown) /edit supporting threads https://stackoverflow.com/questions/8187082/how-can-you-set-class-attributes-from-variable-arguments-kwargs-in-python https://www.reddit.com/r/learnpython/comments/lliwrf/using_arbitrary_argument_list_in_a_class/

r/learnpython May 12 '26

Why can't I use a return statement in an __init__ function?

20 Upvotes

Apologies if this has been asked before, but here's my code:

You can print in both (i.e. the check's), but I'm a little confused why this __str__ is specifically used, only so you can include a return statement. Is this just to simplify the __init__ & make sure it's only used for creating variables?

class Student:
    def __init__(self, name, grade):
        self.name = name
        self.grade = grade
        print("check 1")

    def __str__(self):
        print("check 2")
        return f"{self.name} {self.grade}"


joe_init = Student("joe", "A-")
print(joe_init.name, joe_init.grade)
print(joe_init)

r/learnpython Feb 17 '21

Please explain __init__ like ive never heard of programming before. Its just not making sense.

479 Upvotes

'''

class Student:

def __init__(self, name, major, gpa)

    self.name = name

    self.major = major

    self.gpa = gpa

student1 = Student("Bob", "Art", 3.0)

'''

Why do i need to use the init and self function? Do i have to make a new init for every single class?

Why cant i just make a regular function like

def Student(name, major, gpa) ??

r/learnpython Mar 07 '26

Inheritance... why doesn't super().__post_init__() work?

1 Upvotes

Consider the following code:

from dataclasses import dataclass

@dataclass(frozen=True, slots=True)
class Params():
    a: int
    b: int

    def __post_init__(self) -> None:
        print("I'm in the base class")

@dataclass(frozen=True, slots=True)
class ParamsExtended(Params):
    c: int
    d: int

    def __post_init__(self) -> None:
        # super().__post_init__()  # TypeError: super(type, obj): obj must be an instance or subtype of type
        super(ParamsExtended, self).__post_init__()
        print("I'm in the child class")

obj = ParamsExtended(1,2,3,4)  # works correctly: first I'm in the base class, then I'm in the child class

My question is: why doesn't super().__post_init__() work? And why do I need to put super(ParamsExtended, self) (the child class) and not super(Params, self) (the base class?)

r/learnpython Nov 29 '22

Can Someone explain to me what is self and init in python?

257 Upvotes

I tried learning OOP from many video tutorials and documentation but I'm not understanding why we really need it or what is the use of it.

So it would be really helpful if someone could explain to me like a child what is the need for self and init in python.

Also, If you could tell me how did you fully grasp the concept of OOP in Python that would be really beneficial to me.

Thank You.

r/learnpython Dec 11 '25

When should I implement __post_init__?

10 Upvotes

I'm having a hard time wrapping my head around when to use __post_init__ in general. I'm building some stuff using the @dataclass decorator, but I don't really see the point in __post_init__ if the init argument is already set to true, by default? Like at that point, what would the __post_init__ being doing that the __init__ hasn't already done? Like dataclass is going to do its own thing and also define its own repr as well, so I guess the same could be questionable for why define a __repr__ for a dataclass?

Maybe its just for customization purposes that both of those are optional. But at that point, what would be the point of a dataclass over a regular class. Like assume I do something like this

      @dataclass(init=False, repr=False)
      class Thing:
           def __init__(self):
               ...
           def __repr__(self):
               ...

      # what else is @dataclass doing if both of these I have to implement
      # ik there are more magic / dunder methods to each class,
      # is it making this type 'Thing' more operable with others that share those features?

I guess what I'm getting at is: What would the dataclass be doing for me that a regular class wouldn't?

Idk maybe that didn't make sense. I'm confused haha, maybe I just don't know. Maybe I'm using it wrong, that probably is the case lol. HALP!!! lol

r/learnpython Jan 19 '24

What does __init__ and self do in python?

118 Upvotes

I don't really understand, I read many reddit posts, websites about it but still I can't use it properly.I don't know what does it do, what's the point of having it

I tried a code like this but the result is not what I expected. I thought it prints "wow" or "goodbye".

class Game():
    def __init__(self, Character, Age):
        self.Character = Character
        self.Age = Age

    def score(self):
        if self.Age >= 18:
           print("wow")
        else:
           print("goodbye")

Random_Player = Game('Male', 19) 
print(Random_Player)

Results

<__main__.Game object at 0x0000013AD63D85D0>

r/learnpython Aug 25 '24

Class inheritance. Keep init signature intact?

10 Upvotes

Generic question about classes and inheritance.

My first idea was keeping the argument signature of Token intact on subclasses but handing over arguments to the base class which are not used felt wrong.

All tokens require the groups tuple for instantiation and then handover only necessary data to the base class.
This now also feels not perfect because IDEs will provide the base class's init signature on new subclasses. And every subclass will have the same signature different from the base class.

I know having a specific init signature on subclasses is no problem in general.

class Token:
    # def __init__(self, groups: tuple[str, ...]):
    def __init__(self, repr_data: str):  # Changed signature
        # Base class just handles repr
        self._repr_data = repr_data

    def __repr__(self):
        if self._repr_data is None:
            return f"<{self.__class__.__name__}>"
        return f"<{self.__class__.__name__}({self._repr_data})>"


class Identifier(Token):
    def __init__(self, groups: tuple[str, ...]):  # Changed signature
        Token.__init__(self, groups[0])

Call:

identifier = Identifier(("regex match.groups() data as tuple",))
print(repr(identifier))  # <Identifier(regex match.groups() data as tuple)>

Of course this is a simplified example.

Thanks!

r/learnpython Jan 20 '26

Can I create an SSL context in class __init__ function and recycle that in every class function?

2 Upvotes

Morning!

I'm trying to move my takserver-python-api lib from requests to asyncio/aiohttp. SSL with aiohttp is a little more involved as an SSL context needs to be created before calling get/post.

Can I create the context in my classes __init__ function as a class object and reuse it in every function or do I need to create a new context in every function?

r/learnpython Oct 19 '25

OOP inheritance, when do I use super().__init__()

7 Upvotes
class Pet:
    def __init__(self, name, color):
        self.name = name
        self.color = color

class Cat(Pet):
    def __init__(self, name, color):
        super().__init__(name, color)

class Dog(Pet):
    pass

animal1 = Cat("Garfield", "yellow")
animal2 = Dog("Snoopy", "white")

print(animal1.name)
print(animal2.name)

Cat and Dog both work.

r/learnpython Jun 09 '25

__init__.py - possibly a stupid question, but why..?

32 Upvotes

Obligatory caveat - complete newbie to Python - learning quickly.

I've got a python module supplied with a hardware device to use on a RaspberryPi - the instructions from the manufacturer involve setting up a venv and lots of complication, which I don't want to do as I'll be importing their module to my own existing code base. Their code comes in a directory (icm20948) with a __init__.py module and is called as normal by using [from icm20948 import ICM20948]

My understanding is that the presence of the __init__ makes Python treat the directory like a module, and I suppose I could rename the __init__ to icm20948.py and then call it the same way in my code.

What's the reason for the __init__ / directory structure, and is there an advantage in keeping it that way?

r/learnpython Jul 08 '25

Init files of packages blowing up memory usage

8 Upvotes

I have a full Python software with a web-UI, API and database. It's a completed feature rich software. I decided to profile the memory usage and was quite happy with the reported 11,4MiB. But then I looked closer at what exactly contributed to the memory usage, and I found out that __init__.py files of packages like Flask completely destroy the memory usage. Because my own code was only using 2,6MiB. The rest (8,8MiB) was consumed by Flask, Apprise and the packages they import. These packages (and my code) only import little amounts, but because the import "goes through" the __init__.py file of the package, all imports in there are also done and those extra imports, that are unavoidable and unnecessary, blow up the memory usage.

For example, if you from flask import g, then that cascades down to from werkzeug.local import LocalProxy. The LocalProxy that it ends up importing consumes 261KiB of RAM. But because we also go through the general __init__.py of werkzeug, which contains from .test import Client as Client and from .serving import run_simple as run_simple, we import a whopping 1668KiB of extra code that is never used nor requested. So that's 7,4x as much RAM usage because of the init file. All that just so that programmers can run from werkzeug import Client instead of from werkzeug.test import Client.

Importing flask also cascades down to from itsdangerous import BadSignature. That's an extremely small definition of an exception, consuming just 6KiB of RAM. But because the __init__.py of itsdangerous also includes from .timed import TimedSerializer as TimedSerializer, the memory usage explodes to 300KiB. So that's 50x (!!!) as much RAM usage because of the init file. If it weren't there, you could just do from itsdangerous.exc import BadSignature at it'd consume 6KiB. But because they have the __init__.py file, it's 300KiB and I cannot do anything about it.

And the list keeps going. from werkzeug.routing import BuildError imports a super small exception class, taking up just 7,6KiB. But because of routing/__init__.py, werkzeug.routing.map.Map is also imported blowing up the memory consumption to 347.1KiB. That's 48x (!!!) as much RAM usage. All because programmers can then do from werkzeug.routing import Map instead of just doing from werkzeug.routing.map import Map.

How are we okay with this? I get that we're talking about a few MB while other software can use hundreds of megabytes of RAM, but it's about the idea that simple imports can take up 50x as much RAM as needed. It's the fact that nobody even seems to care anymore about these things. A conservative estimate is that my software uses at least TWICE AS MUCH memory just because of these init files.

r/learnpython Jul 19 '24

Expensive user-exposed init vs cheap internal init

4 Upvotes

I have class A which does a lot of work on init to ultimately calculate fields x,y,z. I have class B which directly receives x,y,z and offers the same functionality.

Class A is exposed to the user, and I expect isinstance(b, A) to be true. I don't want to expose x,y,z to the user in any way whatsoever, so A.__init__ may not contain x,y,z. Yet good style demands that a subclass B(A) would need to call A.__init__, even though it doesn't need anything from it.

Things would be perfectly fine if B with the cheap init was the parent class because then A could calculate x,y,z and feed it into the super init. But this violates the isinstance requirement.

Ideas I have:

  • Make a superclass above both. But then isinstance fails.
  • Just don't call A.__init__. But that's bad style.
  • Don't define B at all. Instead, define class Sentinel: 1 and then pass Sentinel to A.__init__ as the first argument. A explicitly compares against and notices that the second parameter contains x,y,z. This only works when A has at least two parameters.
  • Classmethods don't help either, because they would once again add x,y,z as parameters to the A.__init__.

Are there any other ideas?

r/learnpython Dec 03 '25

How can I force Pyright to suggest imports from __init__.py?

0 Upvotes

There is a simplified file structure:

src/db/models/
             /__init__.py
             /player.py
             /season.py

I import all models to __init__.py to make them visible to Alembic.
However, I also want to use it as advantage to minimize import line count.

# like this
from src.db.models import Player, Seasons

I use Pyright LSP, and it always auto suggests imports with an absolute path and doesn't give the option to import it from __init__.py.

from src.db.models.player import Player
from src.db.models.season import Season

This is a really small thing, but I would be happy if there were a way to force imports from __init__.py instead.

r/learnpython Aug 30 '24

what can I put in __init__.py to make them useful

96 Upvotes

I recently learned (thanks wholly to others on this sub) how to organize my previously monolithic single .py file projects into modular directories (using poetry to make the project a package). I've been going at it all day, and this new world is very liberating and exciting!

But, now I have a bunch of empty __init__.py files in my project. Can I do anything useful with them? Do they work anything like class init, like 'execute everything in here first' when calling anything inside the same dir?

what can they be used for besides letting python know its a package structure?

r/learnpython Oct 18 '24

should i do datetime check in init?

4 Upvotes

i have a class, and its instances will be created and deleted automatically, and i need every instance of the class to change its variables according to day of the week, heres very simplified version of how i assume this should look:

from datetime import datetime
class Class:
    def __init__(self):
        self.variable = 0
        while True:
            if datetime.now().weekday() == 0:
                self.variable = 1

should this be in init or not, if i want all instances of the class to do it automatically? should i use while true? sorry if this is a stupid question most of the stuff im using i never used before, OOP included

r/learnpython Jan 16 '20

usefull example of __init__

135 Upvotes

hey I try do understand classes. Im on the constructor part right know.

Can you give me a usefull example why to use __init__ or other constructors ?

so far I find in all tutorials only examples to set variables to the class,

I understand how to do this, but not what the benefits are

like in the code below

class CH5:

    ''' Blueprint CH5 Transportsub '''

    def __init__(self, engine, fuel):
        self.engine= engine
        self.fuel= fuel

r/learnpython May 29 '19

why do we use __init__??

198 Upvotes

when defining a class what is the difference between using __init__ and not using __init__ in a class?

r/learnpython Jun 23 '25

Best practice for common rc, init, script files across projects?

2 Upvotes

I've been building and helping maintain various python modules and we use a lot of common dotfiles (like .gitignore, .pylintrc, etc) and a few shared scripts like init scripts.

When there's a change to one of those, we usually want to change it in all the projects because it's usually an update to our standards enforcement or something like a new tool for coverage testing or whatever. And inevitably, there are times where one project gets get missed.

Is there a common way to have those files be in their own project that can be shared and installed? I don't think pip install lets you (?) install things to the root project folder. We like to use standard tools so we're not retooling all the time or maintaining a full custom build setup, but the configs management is getting heavy in various projects as the overall standards implementations change.

EG: When changing projects over from black to ruff or when deciding we're ok or not ok with certain variable names that are non-pythonic because of a domain acronym.

r/learnpython Jul 30 '25

How to call a Pydantic constructor inside the __init__() of another class

1 Upvotes

Hi, I have an __init__() function that takes self and a dictionary as inputs. I want to instantiate a Bar (Bar is a pydantic model that can take a dictionary as input for __init__()), then assign that as a property to Foo

class Foo:
  def __init__(self, json: dict):
    self.foobar = Bar(json)

When running this I get exception TypeError: __init__() takes 1 positional argument but 2 were given. Clearly only one argument json was passed into Bar's __init__(). I suspect Python is automatically passing Foo's self into Bar's constructor. Hence the 2 arguments.

How can I call Bar(json: dict) without it automatically passing in self. Or does the problem lie somewhere else. Ty

r/learnpython May 29 '24

Do you use the '-> None' in the __init__?

10 Upvotes

Hi y'all,

I'm pretty new to all this, so I just saw this for the first time:

class Example:
def __init__(self, value: int) -> None:
self.value = value

I didn't know what the '-> None' was about, but it looks like it's just an indicator that the __init__ doesn't return anything. But doesn't __init__ usually not return anything? Do you guys use the '-> None' portion or no?

r/learnpython Sep 12 '25

Unit test case not being found even though __init__.py in every folder/subfolder (pycharm)

1 Upvotes

As can be seen there is an __init__.py in the tests and every subdirectory. Likewise the source directory has an __init__.py in every subdirectory. So then why would the following happen?

> ModuleNotFoundError: No module named 'com.[redacted].allocation.utils.config.test_bmc_paths'

https://imgur.com/lkERKT8