All posts by Emerald

Emerald is a Student of Pure Mathematics at the Federal University of Oye-ekiti. CEO & founder of iCASTE MEDIA. A writer & blogger, passionate about entrepreneurial crafts and loves to promote them too.

Ten Python Development Skills: A SUPER-practical Tutorial

By Pawal Jain

Every now and again, when I learn about a new feature in Python, or I notice that a few others are unaware of a feature, I make a note of it.

Over the last few weeks, there have been a few interesting features that I recently learned about, or realized others — on Stack Overflow

Here are ten neat Python development tricks some I’m sure you haven’t seen before. And a quick look at a few of these features, and a rundown of each.

Note: Codes are shown as images in this story. Further, you will get GitHub Readme link at the end to do experiments further 🤗

01. How to view source code in the running state?

Looking at the source code of the function, we usually use the IDE to complete.

For example, in PyCharm, you can use Ctrl + mouse to enter the source code of the function.

What if there is no IDE?

  • When we want to use a function, how do we know which parameters this function needs to receive?
  • When we have problems when using functions, how to troubleshoot the problem by reading the source code?

At this time, we can use inspect instead of IDE to help you accomplish these things

Image for post

inspect.getsource: Return the text of the source code for an object.

Image for post

The inspect module provides several useful functions to help get information about live objects such as modules, classes, methods, functions, tracebacks, frame objects, and code objects

Four main kinds of services provided by this module:

  • Type checking,
  • Getting source code,
  • Inspecting classes and functions
  • Examining the interpreter stack.

02. The fastest way to view the package path

When you use import to import a package or module, Python will look in some directories, and these directories have a priority order, normally we will use sys.path to view.

Image for post

Is there a faster way?

Here I want to introduce a more convenient method than the above, one line command can be solved

Image for post

From the output, you can find that the path of this column will be more complete than sys.path, which contains the directory of the user environment.

03. Write the nested for a loop as a single line

We often use the following nested for loop code

Image for post

Here are just three for loops, in actual coding, there may be more layers.

Such code is poorly readable, and people do not want to write it, and there is a better way to write it.

Here I introduce a commonly used writing method, using the itertools library to achieve a more elegant and readable code.

Image for post

04. How to use the print output log

Many people like to use print to debug code and record the running process of the program.

However, the print will only output the content to the terminal, and cannot be persisted to the log file, which is not conducive to troubleshooting.

If you are keen to use print to debug code (although this is not the best practice), record the process of running the program, then the print usage described below may be useful to you.

Print it as a function in Python 3, because it can receive more parameters, so the function itself becomes more powerful

code shown as below:

Image for post

05. How to quickly calculate the function running time

Calculate the running time of a function, you might do it like this

Image for post

You see you wrote a few lines of code to calculate the running time of the function.

Is there a way to calculate this running time more conveniently? Yes by using a built-in module called timeit

Use it with just one line of code

Image for post

The results are as follows

2
2
2
2
2
10.020059824

06. Use the built-in caching mechanism to improve efficiency

Caching is a method of storing quantitative data to meet the needs of subsequent acquisitions, and is designed to speed up data acquisition.

The data generation process may require operations such as calculation, regularization, and remote acquisition. If the same piece of data needs to be used multiple times, it will be a waste of time to regenerate each time.

Therefore, if the data obtained by operations such as computing or remote request is cached, the subsequent data acquisition requirements will be accelerated.

To achieve this requirement, Python 3.2+ provides us with a mechanism that can be easily implemented without requiring you to write such a logic code.

This mechanism is implemented in the lru_cache decorator in the functool module.

Image for post

Parameter interpretation:

  • maxsize: how many results of this function call can be cached at most, if None, there is no limit, when set to a power of 2, the performance is the best
  • typed: If True, calls of different parameter types will be cached separately.

for example

Image for post

The output is as follows, you can see that the second call does not execute the function body, but directly returns the result in the cache

calculating: 1 + 2
3
3
calculating: 2 + 3
5

The following is the classic Fibonacci sequence when you specify larger n, there will be a lot of repeated calculations

Image for post

The timeit introduced in point 6 can now be used to test how much efficiency can be improved.

Without lru_cache, the running time is 31 seconds

Image for post

After using lru_cache, the running speed is too fast, so I adjusted the value of n from 30 to 500, but even so, the running time is only 0.0004 seconds. The increase in speed is very significant.

Image for post

07. Tips for executing code before the program exits

Using the built-in module atexit, you can easily register and exit functions.

Wherever you cause the program to crash, it will execute those functions that you have registered. Examples are as follows

Image for post

The results are as follows:

Image for post

If the clean() function has parameters, you can call atexit.register (clean_1parameter 1parameter 2parameter 3=’xxx’) without using decorators.

Maybe you have other ways to deal with this kind of demand, but it is more elegant and convenient than not using atexit, and it is easy to extend.

But using atexit still has some limitations, such as:

  • If the program is killed by a system signal that you have not processed, the registered function cannot be executed normally.
  • If a serious Python internal error occurs, the function you registered cannot be executed normally.
  • If you call it manually os._exit(), the function you registered cannot be executed normally.

08. How to turn off the exception association context?

When you are handling an exception, due to improper handling or other problems, when another exception is thrown, the exception thrown out will also carry the original exception information.

Read it again and you will surely understand it now 🙂

Just like this.

Image for post

You can see two exception messages from the output

Image for post

If an exception is thrown in an exception handler or finally block, the exception mechanism will implicitly work by default to attach the previous exception as the __context__ attribute of the new exception.

This is the automatic correlation exception context that Python enables by default.

If you want to control this context yourself, you can add a from keyword (from will have a limitation that the second expression must be another exception class or instance.) to indicate which exception caused your new exception.

Image for post

The output is as follows

Image for post

Of course, you can also use the with_traceback() method to set the __context__ attribute for exceptions, which can also display exception information better in the traceback.

Image for post

Finally, if I want to completely turn off this mechanism of automatically associating exception contexts? what else can we do?

Can be used raise...from None, from the following example, there is no original exception

Image for post

09. Implement defer-like delayed calls

There is a mechanism for delaying calls in Golang. The keyword is defer, as shown below

Image for post

The call of myfunc will be completed before the function returns, even if you write the call of myfunc on the first line of the function, this is the delayed call. The output is as follows,

A
B

So is there such a mechanism in Python?

Of course, there are, but it is not as simple as Golang.

We can use the Python context managers to achieve this effect

Image for post

The output is as follows

A
B

10. How to stream read large files

Using with…open… we can read data from a file, which is a very familiar operation for all Python devs.

But if you use it improperly, it will also cause great trouble.

For example, when you use the read function, Python will load the contents of the file into memory all at once. If the file has 10 GB or more, then the memory that your computer will consume is very huge.

Image for post

For this problem, you may think of using readline as a generator to return line by line.

Image for post

But if the content of this file is in one line, 10 GB per line you will still read all the contents at once.

The most elegant solution is to use the read method to specify that only the fixed size of the content is read at a time. For example, in the following code, only 8kb is returned at a time.

Image for post

The above code has no problem in function, but the code still looks a bit bloated.

With partial function and iter function, you can optimize the code like this

Image for post

To Sum up

  • We can use inspect to view source code in the running state
  • itertools.product can be used in case of nested loops
  • Use timeit module over time to calculate running time of a function or piece of code
  • Use functool.lru_cache to speed up your code. It’s designed to speed up data acquisition
  • Use atexit module to register your functions so that wherever you cause the program to crash, it will execute those functions that you have registered
  • Read a large file by breaking it into fixed-size blocks

That’s it! Did you learn anything new? Or do you have another trick that you want to share? Please let me know in the comments!

Here is the link for GitHub Readmeto view and analyze each trick

Yeah! now enjoy just like minions 😋, we made it to the end. Hope you learn something new and have some basic idea about these efficient development tricks

Image for post
Source: Giphy

Thanks for reading, We hope you’ve fuel up your python development skill and knowledge. To See more tutorials like this, Support by dropping your comments, likes and share with friends.

Stay connected and see you around👋🏻

Vacancy: Graphic Designer at TAJBank Limited| Location: Abuja

Graphic Designer

  • Job Type: Full Time
  • Qualification: BA/BSc/HND
  • Experience
  • Location: Abuja
  • Job Field: ICT / Computer  , Media / Advertising / Branding 

Seniority Level: Associate
Industry: Financial Services

Job Description

  • The ideal candidate will have strong creative skills and a portfolio of work which demonstrates their passion for illustrative design and typography.
  • This candidate will have experiences in working with numerous different design platforms such as digital and print forms.

Responsibilities

  • Collaborate with the team to ensure consistency of designs across various media outlets
  • Create compelling and effective logos, designs, print and digital media
  • Maintain awareness of current industry and technology standards, social media, competitive landscape and market trends

Qualifications

  • Bachelor’s Degree in Graphic Design or related field
  • Proficient in Adobe Creative Suite
  • Strong communication, conceptual thinking, typography skills and design skills
  • Portfolio of work

Job Functions

  • Design
  • Art/Creative
  • Writing/Editing

Deadline: Not specified

Method of Application

Interested and qualified? Go to TAJBank Limited on www.linkedin.com to 

Vacancy: Subcontractor (Building and Civil Work) at Efficacy Construction Company

Deadline: Jul 22, 2020

Efficacy Homes Limited was incorporated as a limited liability company with RC 765581 in August 2008 to carryout professional and corporate business in Real Estate, Building Construction and Project management. It has her office at idowu taylor, Victoria Island. Lagos. Since inception, Efficacy homes limited has engaged competent professionals in developi…

Job Type: Full Time

Qualification

Experience

Location: Lagos

Job Field: Engineering / Technical Requirement

Requirement

  • Interested candidates should possess relevant qualification.

Method of Application

Interested and qualified candidates should send their CV to: careers@efficacyconstruction.com  

Candidates are to indicate their profession as the subject matter of the mail. For example: “Plumber” or “Builder” as the case may be

Vacancy: Logistics Coordinator at Transport Services Limited (TSL)

Logistics Coordinator

  • Job Type: Full Time
  • Qualification: BA/BSc/HND
  • Experience – 2 years
  • Location: Lagos
  • Job Field: Logistics 

Description

  • Maximizing revenue by ensuring trip targets are achieved.
  • Disbursement of loading fees and trip allowance to drivers.
  • Collating and processing Driver waybills for invoicing.
  • Compilation of daily expense reports from all depots.
  • Coordinate the inspection of truck calibration charts on a monthly basis and tracking of expiry dates.
  • Conduct pre-trip briefing for drivers and ensure journey plan is issued before dispatch of trucks from the loading plant/location.
  • Record and share a journey plan on the trip analysis sheet with stakeholders within the Operations and Journey Management Control Centre.

Requirement/ Qualification

  • Minimum of a B.Sc certification.
  • 0-2 Years Post NYSC experience.

Deadline: July 17, 2020

Interested and qualified? Go to Transport Services Limited on airtable.com to apply

Vacancy: Business Development Officer| Location: Lekki

Owens and Xley is a business consulting and advisory company. We offer strategic services in the areas of business advisory, business development and planning to small businesses that would otherwise not have access to the technical competencies available to bigger companies.

Business Development Officer

  • Job Type: Full Time
  • Qualification
  • Experience: None
  • Location: Lagos
  • Job Field: Sales / Marketing / Retail / Business Development 

Our client, a leading and award winning fashion brand is currently recruiting a suitably qualified candidate to fill the position below:

Location: Lekki

Overview

The Business Development Officer is responsible for increasing sales and profits for the company, finding new business opportunities and strategic business growth. You are responsible for analyzing customer feedback and data to determine how customers are patronizing us and then develop a strategic plan to increase new and return purchases, or discontinue underperforming offerings.

Job Description

  • Create and maintain a proactive relationship with our clients.
  • Work proactively to determine and propose our marketing needs.
  • Prioritize and manage multiple projects simultaneously, and follow through on issues in a timely manner.
  • Drive brand awareness online through social media, and offline via daily door to door marketing activities.
  • Maintain the customers and seller’s database to drive email marketing initiatives.
  • Grow and meet the new names target of the company.
  • Meet the monthly sales revenue target of the company.
  • Vendor engagement and management.
  • Work with the CEO in creating an overall Marketing Strategy for the business; creating presentations as well as writing proposals and customer engagement strategies.
  • Responsible for staying informed on activities that are being performed on our accounts
  • and ensure ALL important documentation/deliverables align with overall strategy.
  • Prepare weekly reports and month-end overviews of our current activities, and monthly revenue forecasts, plus plans for future business development.
  • Organize successful pop up shops and, online and offline events to drive sales.

Skills and competencies

  • Excellent written and verbal communication skills.
  • Comfortable with CRM software.
  • Ability to think creatively and innovatively.
  • Analytical skills to forecast and identify trends and challenges.
  • Familiarity with the latest trends, technologies and methodologies in small business strategy, marketing, branding etc.
  • Must be self-driven and proactive.
  • Organisational and planning skills.
  • Problem solving skills.
  • Attention to detail
  • Flexible
  • Effective at managing change in a fast-moving and constantly evolving business.
  • Ability to work with little or no supervision.

Salary:

55,000

Commission on monthly sales revenue

Deadline: July 10, 2020

Method of Application

Interested and qualified candidates should forward their CV to: recruitment@owensxley.com using the position as subject of email.

Vacancy: Field Specialist at Traderofafrica.com| Location- Lagos

Field Specialist

  • Job Type: Full Time
  • Qualification: BA/BSc/HND
  • Experience
  • Location: Lagos
  • Job Field: Sales / Marketing / Retail / Business Development 

Locations: Lagos and Cameroon
Reports To: Sourcepro Team Lead and Lead, Field Operation Specialist

Job Overview

  • The Field Specialist will primarily be responsible for monitoring and supervising products brought by suppliers (Timber/Wood) and monitor the exporting processes of such product to buyer’s destination
  • Also acquisition / sourcing for potential new buyer and new suppliers.

Responsibilities and Duties

  • Travel to product locations.
  • Plan and coordinate the shipping activities.
  • Strategise and execute sourcing from various African countries.
  • Know your product (Timber/Wood/Charcoal/ Agro commodities).
  • Source for new suppliers.
  • Source for new Buyers.
  • Provide week activities report.
  • Inspect product in the forest, park or warehouse.
  • Send photos and videos of product.
  • Supervise movement.

Requirements

  • Relevant academic qualification – minimum of a B.Sc is required.
  • Must be tech savvy and ready to learn.
  • Must have an international passport and ready to travel.
  • Previous experience in a related field is an advantage.
  • Must be willing to be away from home for a period of time.
  • Must have good computing skills.
  • Must be fluent in verbal and written English.
  • And any other language is an advantage (French)
  • Must be a bit rugged and sharp
  • Hardworking, Focused and dedicated.
  • Strong and energetic.

Deadline: July 15, 2020

Method of Application

Interested and qualified candidates should send their CV to: joy@tradersofafrica.com  , parkinson@tradersofafrica.com  using the Job Title as the subject of the mail.

Vacancy: Business Development Executive (Furniture Factory) at Don Quester Consulting| Location- Lagos

  • Job Type: Full Time
  • Qualification: BA/BSc/HND
  • Experience: 5 years
  • Location: Lagos
  • Job Field: Sales / Marketing / Retail / Business Development 

Job Code: BDEF-002
Location: Lekki, Lagos

Job Responsibilities

  • Ability to research and identify new sales leads and market opportunities.
  • Ability to prepare and deliver pitches to potential products and oversee the sales process to attract new clients.
  • Ability to create, monitor and analyze marketing data, sales interventions/strategy, and achieve sales activity goals such as locating, developing, negotiating and closing business to meet sales target.
  • Ability to build and maintain key customer relationships with clients and address their needs effectively
  • Ability to define long-term organizational goals and work with team members to identify and manage risks.
  • Ability to improve the organization’s market position, achieve financial growth and maintain extensive knowledge of current market conditions.

Qualifications

  • B.Sc/HND in marketing or communications related field with certification in sales/marketing.
  • Minimum of 5 years proven post qualification/experience as a business developer in the manufacturing sector.

Deadline: July 14, 2020

Method of Application

Note: Only shortlisted candidates would be contacted and scheduled for interview.Interested and qualified? Go to Don Quester Consulting on donquester.com to apply

Vacancy: Sales Representative – Ascentech| Location: Ogun

Sales Representative

  • Job Type: Full Time
  • Qualification: BA/BSc/HND
  • Experience: 1 – 2 years
  • Location: Ogun
  • Job Field: Sales / Marketing / Retail / Business Development 

Deadline: July 31


Location: Ota, Ogun

Responsibilities

  • Create customer database by sourcing for customers
  • Meet daily, weekly, monthly and quarterly sales quotas
  • Prepare and submit weekly sales reports to management
  • Assist other team members with transactions when necessary

Requirements

  • HND / B.Sc Degree in Marketing or any other related field
  • 1-2 years of experience sales experience in an FMCG food-based company
  • Experience working with sales volumes
  • Go getter, Personable, team player with good relationships skills.
  • Must be computer literate with a practical and working knowledge of Microsoft office.
  • Willingness to work from alternate store locations when needed
  • Should have a working knowledge of Lagos and its environs and Ogun State.

Method of Application

Interested and qualified candidates should forward their CV to: cv@ascentech.com.ng  using the position as subject of the email.

Note: Only shortlisted candidates will be contacted.

Vacancy: Marketers needed at Coinbox Limited|Location- Lagos

Marketer at Coinbox Limited

About company in Brief:
Coinbox Limited is a multi-dimensional Consulting Firm which provides one-stop total business development and support to our vast clientele of start-ups, Small, Medium, growing and Large Enterprises, Cooperative Societies, Groups and Associations. We support and create ideas, we provide solutions and we create systems.

Marketer
• Job Type: Full Time
• Qualification: OND
• Experience: 1 – 3 years
• Location: Lagos
• Job Field: Sales / Marketing / Retail / Business Development

Our client, a Manufacturing Company into the production of consumables like Poundo yam, rice etc, urgently seeks to hire marketers.
Location: Ogudu, Lagos.
Qualification Requirement:
Minimum OND

Skills Required:
• Good marketing skills and excellent communication skills (oral and written).
• 1-3 years of marketing experience
• Ability to drive
• Ability to work with little or no supervision.
• Target oriented, self-motivated and a go-getter.

Responsibilities:
• Directly responsible for effectively marketing the company’s products (FMCG)
• To recommend any marketing initiatives that may assist in achieving monthly sales volume. ETC
Remuneration: Basic + Commission

Deadline: July 12, 2020

Method of Application
Interested and qualified candidates should forward their CV to: recruitment@coinboxlimited.com.ng using the position as subject of email.

Access Bank Opens W Initiative Womenpreneur Pitch-a-ton Africa 2020 for Women Entrepreneurs(Ends 14th August)

Launched in 2019, the Womenpreneur Pitch-a-ton Africa was the first women-in-business support initiative of its kind in the industry offered by the Access Bank W Initiative. The program in its maiden edition provided financial grants worth N9Million to the top 5 applicants with a free mini MBA certification for 50 women entrepreneurs in Nigeria. This it did in conjunction with the International Finance Corporation (IFC, a member of the World Bank Group).
https://twitter.com/access_more/status/1275111966466551815?s=19

This year, the program is being extended to 6 other African countries where Access Bank’s W initiative has its presence. These countries are Nigeria, Ghana, Rwanda, Zambia, Sierra-Leone, Gambia and Congo hence the tag name “Womenpreneur Pitch-A-Ton Africa

ELIGIBILITY

  • Woman who owns and runs her business
  • Business innovative
  • Need a grant to expand your business
  • Need some expert training to help grow your business

BENEFITS

A. The Womenpreneur Pitch-a-ton Africa 2020 will provide up to N9 million financial grant and a unique capacity building program aimed at empowering women entrepreneurs.

B. The programme is designed as a 3-month period incorporating pitching sessions and 8 weeks of mini-MBA training in collaboration with the IFC.

C. Interested persons from Nigeria, Ghana, Zambia and Rwanda as well as with extension to Sierra Leone, Gambia, & Congo who meet the criteria are required to fill an online application. The five hundred candidates
selected from this pool will then send in a sixty seconds video pitch which will be screened by a credible panel of business experts to select fifty finalists.

D. As part of the graduation requirements, the fifty finalists will pitch their businesses, infusing learnings from the mini-MBA and will stand an opportunity to win financial grants up to N5 million.

OFFICIAL LINK

http://www.womenpreneur.ng/
Deadline: 14th of August 2020