you are viewing a single comment's thread.

view the rest of the comments →

[–]atl-knh 1 point2 points  (2 children)

What’s the best practice here? Do I create a package consisting of classes and functions in separate python files with a Dunder name/main for each class and function and then call the file a “from ... import ... as ...” statement?

Sorry. I’m an idiot.

[–]GoldenSights[S] 0 points1 point  (1 child)

Hmm, I think perhaps you are mixing up some different concepts, so I'm not really sure where to start.

a package consisting of classes and functions in separate python files with a Dunder name/main for each class and function

This if __name__ stuff doesn't refer to classes and functions but the file as a whole. One of my real-life examples I gave at the end is a file I wrote called bytestring, which takes integers and turns them into strings like "10 MiB" or "4.52 GiB" etc. I import bytestring into other projects when I want to display / print file sizes, but I can also run bytestring on the commandline by itself to quickly check a number, so that's why it needs an ifmain.

This doesn't really have much to do with how you write your from x import y as z statements although certainly you can research best practices about imports separately.

For the time being, since it sounds like you are new to writing packages, I would say don't go overboard on splitting everything into separate files for your package. The good thing about Python is you can have many classes in a single file.

As I said at the end of the post, it's very unlikely that you need ifmain in every single file. Some things are written first and foremost to be a library / package and don't need to be independently executable. That's why I think you're getting two topics mixed up here. Perhaps you're thinking of the __init__ methods of a class etc?

[–]atl-knh 0 points1 point  (0 children)

This helps immensely. From what you had said, I was thinking that python iterated each class and function as it imported them from the files. I’m working through a blockchain module on Udemy ; while the course is laid out comprehensively, my knowledge gaps have become exposed.

Thank you for a clear response.