Python: Absolute Imports

In Python, Absolute imports can be done in 3 ways. Let's say we have a project structure as below























Let's say you have so many classes and functions inside the products module then we can go with the below syntax.

        
            
            from ecommerce import products
            product = products.Product()
        
    


If we have only one or two classes then we can use the below syntax.

        
  			from ecommerce.products import Product
			product = Product()
		

The last method is very rarely used and I don't see anywhere it's being used, but it's good to know for a specific use case. Let's say you have two but different modules named products and if you want to import both of them, if you follow any of the above methods, for sure you will get name conflict issues. To avoid that you can follow the below syntax

        
  	import ecommerce.products
	product = ecommenrce.products.Product()
    
    

Hope that helps.
Raja


0 comments:

Post a Comment